Skip to content

Commit 06d3061

Browse files
authored
Allow pools to be reusable (#108)
Fixes #103. See inline comments for rationale.
1 parent 1d4991d commit 06d3061

2 files changed

Lines changed: 24 additions & 0 deletions

File tree

pool/pool.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,10 @@ func (p *Pool) Wait() {
7676

7777
close(p.tasks)
7878

79+
// After Wait() returns, reset the struct so tasks will be reinitialized on
80+
// next use. This better matches the behavior of sync.WaitGroup
81+
defer func() { p.initOnce = sync.Once{} }()
82+
7983
p.handle.Wait()
8084
}
8185

pool/pool_test.go

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,26 @@ func TestPool(t *testing.T) {
122122
p := New().WithMaxGoroutines(42)
123123
require.Equal(t, 42, p.MaxGoroutines())
124124
})
125+
126+
t.Run("is reusable", func(t *testing.T) {
127+
t.Parallel()
128+
var count atomic.Int64
129+
p := New()
130+
for i := 0; i < 10; i++ {
131+
p.Go(func() {
132+
count.Add(1)
133+
})
134+
}
135+
p.Wait()
136+
require.Equal(t, int64(10), count.Load())
137+
for i := 0; i < 10; i++ {
138+
p.Go(func() {
139+
count.Add(1)
140+
})
141+
}
142+
p.Wait()
143+
require.Equal(t, int64(20), count.Load())
144+
})
125145
}
126146

127147
func BenchmarkPool(b *testing.B) {

0 commit comments

Comments
 (0)