Skip to content

Commit 1e08883

Browse files
committed
device: fix WaitPool sync.Cond usage
The sync.Locker used with a sync.Cond must be acquired when changing the associated condition, otherwise there is a window within sync.Cond.Wait() where a wake-up may be missed. Fixes: 4846070 ("device: use a waiting sync.Pool instead of a channel") Signed-off-by: Jordan Whited <[email protected]>
1 parent 03c5a0c commit 1e08883

File tree

2 files changed

+9
-7
lines changed

2 files changed

+9
-7
lines changed

device/pools.go

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,14 +7,13 @@ package device
77

88
import (
99
"sync"
10-
"sync/atomic"
1110
)
1211

1312
type WaitPool struct {
1413
pool sync.Pool
1514
cond sync.Cond
1615
lock sync.Mutex
17-
count atomic.Uint32
16+
count uint32 // Get calls not yet Put back
1817
max uint32
1918
}
2019

@@ -27,10 +26,10 @@ func NewWaitPool(max uint32, new func() any) *WaitPool {
2726
func (p *WaitPool) Get() any {
2827
if p.max != 0 {
2928
p.lock.Lock()
30-
for p.count.Load() >= p.max {
29+
for p.count >= p.max {
3130
p.cond.Wait()
3231
}
33-
p.count.Add(1)
32+
p.count++
3433
p.lock.Unlock()
3534
}
3635
return p.pool.Get()
@@ -41,7 +40,9 @@ func (p *WaitPool) Put(x any) {
4140
if p.max == 0 {
4241
return
4342
}
44-
p.count.Add(^uint32(0))
43+
p.lock.Lock()
44+
defer p.lock.Unlock()
45+
p.count--
4546
p.cond.Signal()
4647
}
4748

device/pools_test.go

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,6 @@ import (
1515
)
1616

1717
func TestWaitPool(t *testing.T) {
18-
t.Skip("Currently disabled")
1918
var wg sync.WaitGroup
2019
var trials atomic.Int32
2120
startTrials := int32(100000)
@@ -32,7 +31,9 @@ func TestWaitPool(t *testing.T) {
3231
wg.Add(workers)
3332
var max atomic.Uint32
3433
updateMax := func() {
35-
count := p.count.Load()
34+
p.lock.Lock()
35+
count := p.count
36+
p.lock.Unlock()
3637
if count > p.max {
3738
t.Errorf("count (%d) > max (%d)", count, p.max)
3839
}

0 commit comments

Comments
 (0)