Skip to content

Commit 14be23e

Browse files
zephyrtroniumgopherbot
authored andcommitted
semaphore: cancel acquisition with a done context
When acquiring from a semaphore could proceed without contention, the previous behavior was to always do so, even when the provided context was done. This was the documented behavior, but it could lead to confusion. It isn't much more expensive to check the context error, so cancel acquisition if it's done. Fixes golang/go#63615. goos: linux goarch: amd64 pkg: golang.org/x/sync/semaphore cpu: 12th Gen Intel(R) Core(TM) i5-1235U │ old.bench │ new.bench │ │ sec/op │ sec/op vs base │ AcquireSeq/Weighted-acquire-1-1-1-12 26.45n ± 2% 27.25n ± 3% +3.04% (p=0.001 n=20) AcquireSeq/Weighted-acquire-2-1-1-12 26.96n ± 1% 27.12n ± 1% ~ (p=0.104 n=20) AcquireSeq/Weighted-acquire-16-1-1-12 26.07n ± 3% 27.48n ± 1% +5.45% (p=0.000 n=20) AcquireSeq/Weighted-acquire-128-1-1-12 26.19n ± 2% 27.24n ± 1% +4.01% (p=0.000 n=20) AcquireSeq/Weighted-acquire-2-2-1-12 25.61n ± 1% 25.99n ± 2% ~ (p=0.066 n=20) AcquireSeq/Weighted-acquire-16-2-8-12 209.6n ± 2% 211.0n ± 3% ~ (p=0.280 n=20) AcquireSeq/Weighted-acquire-128-2-64-12 1.669µ ± 1% 1.721µ ± 2% +3.09% (p=0.000 n=20) AcquireSeq/Weighted-acquire-2-1-2-12 51.08n ± 1% 53.03n ± 2% +3.82% (p=0.000 n=20) AcquireSeq/Weighted-acquire-16-8-2-12 52.48n ± 2% 53.66n ± 2% +2.26% (p=0.028 n=20) AcquireSeq/Weighted-acquire-128-64-2-12 52.27n ± 1% 53.71n ± 2% +2.75% (p=0.000 n=20) geomean 60.06n 61.69n +2.71% Change-Id: I0ae1a0bb6c027461ac1a9ee71c51efd8427ab308 Reviewed-on: https://go-review.googlesource.com/c/sync/+/536275 Auto-Submit: Bryan Mills <[email protected]> Reviewed-by: Bryan Mills <[email protected]> Reviewed-by: Michael Knyszek <[email protected]> LUCI-TryBot-Result: Go LUCI <[email protected]>
1 parent 59c1ca1 commit 14be23e

File tree

2 files changed

+68
-9
lines changed

2 files changed

+68
-9
lines changed

semaphore/semaphore.go

+33-9
Original file line numberDiff line numberDiff line change
@@ -35,11 +35,25 @@ type Weighted struct {
3535
// Acquire acquires the semaphore with a weight of n, blocking until resources
3636
// are available or ctx is done. On success, returns nil. On failure, returns
3737
// ctx.Err() and leaves the semaphore unchanged.
38-
//
39-
// If ctx is already done, Acquire may still succeed without blocking.
4038
func (s *Weighted) Acquire(ctx context.Context, n int64) error {
39+
done := ctx.Done()
40+
4141
s.mu.Lock()
42+
select {
43+
case <-done:
44+
// ctx becoming done has "happened before" acquiring the semaphore,
45+
// whether it became done before the call began or while we were
46+
// waiting for the mutex. We prefer to fail even if we could acquire
47+
// the mutex without blocking.
48+
s.mu.Unlock()
49+
return ctx.Err()
50+
default:
51+
}
4252
if s.size-s.cur >= n && s.waiters.Len() == 0 {
53+
// Since we hold s.mu and haven't synchronized since checking done, if
54+
// ctx becomes done before we return here, it becoming done must have
55+
// "happened concurrently" with this call - it cannot "happen before"
56+
// we return in this branch. So, we're ok to always acquire here.
4357
s.cur += n
4458
s.mu.Unlock()
4559
return nil
@@ -48,7 +62,7 @@ func (s *Weighted) Acquire(ctx context.Context, n int64) error {
4862
if n > s.size {
4963
// Don't make other Acquire calls block on one that's doomed to fail.
5064
s.mu.Unlock()
51-
<-ctx.Done()
65+
<-done
5266
return ctx.Err()
5367
}
5468

@@ -58,14 +72,14 @@ func (s *Weighted) Acquire(ctx context.Context, n int64) error {
5872
s.mu.Unlock()
5973

6074
select {
61-
case <-ctx.Done():
62-
err := ctx.Err()
75+
case <-done:
6376
s.mu.Lock()
6477
select {
6578
case <-ready:
66-
// Acquired the semaphore after we were canceled. Rather than trying to
67-
// fix up the queue, just pretend we didn't notice the cancelation.
68-
err = nil
79+
// Acquired the semaphore after we were canceled.
80+
// Pretend we didn't and put the tokens back.
81+
s.cur -= n
82+
s.notifyWaiters()
6983
default:
7084
isFront := s.waiters.Front() == elem
7185
s.waiters.Remove(elem)
@@ -75,9 +89,19 @@ func (s *Weighted) Acquire(ctx context.Context, n int64) error {
7589
}
7690
}
7791
s.mu.Unlock()
78-
return err
92+
return ctx.Err()
7993

8094
case <-ready:
95+
// Acquired the semaphore. Check that ctx isn't already done.
96+
// We check the done channel instead of calling ctx.Err because we
97+
// already have the channel, and ctx.Err is O(n) with the nesting
98+
// depth of ctx.
99+
select {
100+
case <-done:
101+
s.Release(n)
102+
return ctx.Err()
103+
default:
104+
}
81105
return nil
82106
}
83107
}

semaphore/semaphore_test.go

+35
Original file line numberDiff line numberDiff line change
@@ -200,3 +200,38 @@ func TestAllocCancelDoesntStarve(t *testing.T) {
200200
}
201201
sem.Release(1)
202202
}
203+
204+
func TestWeightedAcquireCanceled(t *testing.T) {
205+
// https://go.dev/issue/63615
206+
sem := semaphore.NewWeighted(2)
207+
ctx, cancel := context.WithCancel(context.Background())
208+
sem.Acquire(context.Background(), 1)
209+
ch := make(chan struct{})
210+
go func() {
211+
// Synchronize with the Acquire(2) below.
212+
for sem.TryAcquire(1) {
213+
sem.Release(1)
214+
}
215+
// Now cancel ctx, and then release the token.
216+
cancel()
217+
sem.Release(1)
218+
close(ch)
219+
}()
220+
// Since the context closing happens before enough tokens become available,
221+
// this Acquire must fail.
222+
if err := sem.Acquire(ctx, 2); err != context.Canceled {
223+
t.Errorf("Acquire with canceled context returned wrong error: want context.Canceled, got %v", err)
224+
}
225+
// There must always be two tokens in the semaphore after the other
226+
// goroutine releases the one we held at the start.
227+
<-ch
228+
if !sem.TryAcquire(2) {
229+
t.Fatal("TryAcquire after canceled Acquire failed")
230+
}
231+
// Additionally verify that we don't acquire with a done context even when
232+
// we wouldn't need to block to do so.
233+
sem.Release(2)
234+
if err := sem.Acquire(ctx, 1); err != context.Canceled {
235+
t.Errorf("Acquire with canceled context returned wrong error: want context.Canceled, got %v", err)
236+
}
237+
}

0 commit comments

Comments
 (0)