1 // Copyright 2019 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
13 // TestSemaHandoff checks that when semrelease+handoff is
14 // requested, the G that releases the semaphore yields its
15 // P directly to the first waiter in line.
16 // See issue 33747 for discussion.
17 func TestSemaHandoff(t *testing.T) {
20 for i := 0; i < iter; i++ {
21 if testSemaHandoff() {
25 // As long as two thirds of handoffs are direct, we
26 // consider the test successful. The scheduler is
27 // nondeterministic, so this test checks that we get the
28 // desired outcome in a significant majority of cases.
29 // The actual ratio of direct handoffs is much higher
30 // (>90%) but we use a lower threshold to minimize the
31 // chances that unrelated changes in the runtime will
32 // cause the test to fail or become flaky.
34 t.Fatal("direct handoff < 2/3:", ok, iter)
38 func TestSemaHandoff1(t *testing.T) {
39 if GOMAXPROCS(-1) <= 1 {
40 t.Skip("GOMAXPROCS <= 1")
42 defer GOMAXPROCS(GOMAXPROCS(-1))
47 func TestSemaHandoff2(t *testing.T) {
48 if GOMAXPROCS(-1) <= 2 {
49 t.Skip("GOMAXPROCS <= 2")
51 defer GOMAXPROCS(GOMAXPROCS(-1))
56 func testSemaHandoff() bool {
58 done := make(chan struct{})
60 // We're testing that the current goroutine is able to yield its time slice
61 // to another goroutine. Stop the current goroutine from migrating to
62 // another CPU where it can win the race (and appear to have not yielded) by
63 // keeping the CPUs slightly busy.
64 for i := 0; i < GOMAXPROCS(-1); i++ {
79 atomic.CompareAndSwapUint32(&res, 0, 1)
81 Semrelease1(&sema, true, 0)
84 for SemNwait(&sema) == 0 {
85 Gosched() // wait for goroutine to block in Semacquire
88 // The crux of the test: we release the semaphore with handoff
89 // and immediately perform a CAS both here and in the waiter; we
90 // want the CAS in the waiter to execute first.
91 Semrelease1(&sema, true, 0)
92 atomic.CompareAndSwapUint32(&res, 0, 2)
94 <-done // wait for goroutines to finish to avoid data races
96 return res == 1 // did the waiter run first?