Skip to content

Commit

Permalink
workerpool: make it so Drain() never returns nil
Browse files Browse the repository at this point in the history
Before this patch, Drain() would return nil when no tasks were
submitted.

This patch make it so Drain() always returns a non-nil slice for
consistency.

Signed-off-by: Alexandre Perrin <alex@kaworu.ch>
  • Loading branch information
kaworu committed May 20, 2022
1 parent e2382f4 commit dc85e3a
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
3 changes: 2 additions & 1 deletion workerpool.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ func New(n int) *WorkerPool {
wp := &WorkerPool{
workers: make(chan struct{}, n),
tasks: make(chan *task),
results: []Task{},
}
ctx, cancel := context.WithCancel(context.Background())
wp.cancel = cancel
Expand Down Expand Up @@ -127,7 +128,7 @@ func (wp *WorkerPool) Drain() ([]Task, error) {
// wp.results as no other routine is running at this point besides the
// "run" routine which should be waiting on the tasks channel.
res := wp.results
wp.results = nil
wp.results = []Task{}

wp.mu.Lock()
wp.draining = false
Expand Down
30 changes: 30 additions & 0 deletions workerpool_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,36 @@ func TestWorkerPool(t *testing.T) {
}
}

func TestDrainWithoutSubmit(t *testing.T) {
n := runtime.NumCPU()
wp := workerpool.New(n)

results, err := wp.Drain()
switch {
case err != nil:
t.Errorf("draining failed: %v", err)
case results == nil:
t.Errorf("unexpected nil Drain() results")
case len(results) != 0:
t.Errorf("got %d; want 0", len(results))
}

// test a second time as Drain() reset the results.
results, err = wp.Drain()
switch {
case err != nil:
t.Errorf("draining failed: %v", err)
case results == nil:
t.Errorf("unexpected nil Drain() results")
case len(results) != 0:
t.Errorf("got %d; want 0", len(results))
}

if err := wp.Close(); err != nil {
t.Errorf("close: got '%v', want no error", err)
}
}

func TestConcurrentDrain(t *testing.T) {
n := runtime.NumCPU()
wp := workerpool.New(n)
Expand Down

0 comments on commit dc85e3a

Please sign in to comment.