From 5e03cf18af837757be75bf3e6f437df125ed7560 Mon Sep 17 00:00:00 2001 From: Corentin Clabaut Date: Mon, 8 Jul 2024 08:36:41 +0200 Subject: [PATCH 1/2] Return context in Stop() to notify user when everything has been stopped --- pond.go | 9 +++++++-- pond_blackbox_test.go | 4 ++-- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/pond.go b/pond.go index e5e6192..cb4181d 100644 --- a/pond.go +++ b/pond.go @@ -318,8 +318,13 @@ func (p *WorkerPool) SubmitBefore(task func(), deadline time.Duration) { // Stop causes this pool to stop accepting new tasks and signals all workers to exit. // Tasks being executed by workers will continue until completion (unless the process is terminated). // Tasks in the queue will not be executed. -func (p *WorkerPool) Stop() { - go p.stop(false) +func (p *WorkerPool) Stop() context.Context { + ctx, cancel := context.WithCancel(context.Background()) + go func() { + p.stop(false) + cancel() + }() + return ctx } // StopAndWait causes this pool to stop accepting new tasks and then waits for all tasks in the queue diff --git a/pond_blackbox_test.go b/pond_blackbox_test.go index ca10b11..40a2aec 100644 --- a/pond_blackbox_test.go +++ b/pond_blackbox_test.go @@ -120,7 +120,7 @@ func TestSubmitAndStopWithoutWaiting(t *testing.T) { <-started // Stop without waiting for the rest of the tasks to start - pool.Stop() + ctx := pool.Stop() // Let the first task complete now completed <- true @@ -129,7 +129,7 @@ func TestSubmitAndStopWithoutWaiting(t *testing.T) { assertEqual(t, int32(1), atomic.LoadInt32(&doneCount)) // Make sure the exit lines in the worker pool are executed and covered - time.Sleep(6 * time.Millisecond) + <-ctx.Done() } func TestSubmitWithNilTask(t *testing.T) { From 415243171410a829c7357a6af3bd440383aa0826 Mon Sep 17 00:00:00 2001 From: Corentin Clabaut <7072139+CorentinClabaut@users.noreply.github.com> Date: Wed, 10 Jul 2024 13:20:01 +0200 Subject: [PATCH 2/2] Add comment to Stop() method to explain what the returned context does Co-authored-by: Alejandro Durante --- pond.go | 1 + 1 file changed, 1 insertion(+) diff --git a/pond.go b/pond.go index cb4181d..f176537 100644 --- a/pond.go +++ b/pond.go @@ -318,6 +318,7 @@ func (p *WorkerPool) SubmitBefore(task func(), deadline time.Duration) { // Stop causes this pool to stop accepting new tasks and signals all workers to exit. // Tasks being executed by workers will continue until completion (unless the process is terminated). // Tasks in the queue will not be executed. +// This method returns a context object that is cancelled when the pool has stopped completely. func (p *WorkerPool) Stop() context.Context { ctx, cancel := context.WithCancel(context.Background()) go func() {