From d2061b51372834f5ddc82c847c0192c4389803c3 Mon Sep 17 00:00:00 2001 From: Robin Hahling Date: Wed, 3 Feb 2021 13:48:58 +0100 Subject: [PATCH 1/2] add comment to explain why it's not necessary to hold a lock on results Signed-off-by: Robin Hahling --- workerpool.go | 3 +++ 1 file changed, 3 insertions(+) diff --git a/workerpool.go b/workerpool.go index ef233bc..e7fe85c 100644 --- a/workerpool.go +++ b/workerpool.go @@ -120,6 +120,9 @@ func (wp *WorkerPool) Drain() ([]Task, error) { wp.wg.Wait() + // It's not necessary to hold a lock when reading wp.results as no other + // routine is running at this point besides the "run" routine which should + // be waiting on the tasks channel. res := make([]Task, len(wp.results)) for i, t := range wp.results { res[i] = t From 9ca51644616a3bdcce5727882c65bcf406e61d0e Mon Sep 17 00:00:00 2001 From: Robin Hahling Date: Wed, 3 Feb 2021 13:49:48 +0100 Subject: [PATCH 2/2] wait the for "run" routine to return on Close Signed-off-by: Robin Hahling --- workerpool.go | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/workerpool.go b/workerpool.go index e7fe85c..40268f2 100644 --- a/workerpool.go +++ b/workerpool.go @@ -70,6 +70,7 @@ func (wp *WorkerPool) run() { <-wp.workers }() } + close(wp.workers) } // Submit submits f for processing by a worker. The given id is useful for @@ -153,5 +154,8 @@ func (wp *WorkerPool) Close() error { // At this point, all routines have returned. This means that Submit is not // pending to write to the task channel and it is thus safe to close it. close(wp.tasks) + + // wait for the "run" routine + <-wp.workers return nil }