Skip to content

Commit

Permalink
Improve worker task handling and add pool tests
Browse files Browse the repository at this point in the history
- Changed the worker task channel to be buffered to prevent blocking when submitting tasks.
- Added a new test file, pool_test.go, to test the Submit function of the pool.
- The test ensures that all tasks are executed and that there are no running workers left after all tasks are done.

Signed-off-by: Daniel Hu <tao.hu@merico.dev>
  • Loading branch information
daniel-hutao committed Jul 14, 2023
1 parent 678a72b commit 6088427
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 2 deletions.
4 changes: 2 additions & 2 deletions pool.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ type Pool struct {
// lock represents a mutex to protect the workers slice
lock sync.Mutex
// cond represents a condition variable to manage the pool
cond *sync.Cond
cond *sync.Cond
}

func NewPool(capacity int) *Pool {
Expand All @@ -38,7 +38,7 @@ func (p *Pool) Submit(task Task) {
if worker == nil {
worker = &Worker{
pool: p,
task: make(chan Task),
task: make(chan Task, 1),
}
}
worker.task <- task
Expand Down
27 changes: 27 additions & 0 deletions pool_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package gopool

import (
"sync"
"testing"
)

func TestSubmit(t *testing.T) {
var wg sync.WaitGroup
p := NewPool(10)

for i := 0; i < 20; i++ {
wg.Add(1)
taskNum := i // Capture the task number
task := func() {
t.Logf("Executing task %d\n", taskNum)
defer wg.Done()
}
p.Submit(task)
}

wg.Wait()

if p.Running() != 0 {
t.Errorf("Expected running workers to be 0, but got %d", p.Running())
}
}

0 comments on commit 6088427

Please sign in to comment.