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.
4
5package runtime_test
6
7import (
8	. "runtime"
9	"sync/atomic"
10	"testing"
11)
12
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.
17func TestSemaHandoff(t *testing.T) {
18	const iter = 10000
19	ok := 0
20	for i := 0; i < iter; i++ {
21		if testSemaHandoff() {
22			ok++
23		}
24	}
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.
33	if ok < iter*2/3 {
34		t.Fatal("direct handoff < 2/3:", ok, iter)
35	}
36}
37
38func TestSemaHandoff1(t *testing.T) {
39	if GOMAXPROCS(-1) <= 1 {
40		t.Skip("GOMAXPROCS <= 1")
41	}
42	defer GOMAXPROCS(GOMAXPROCS(-1))
43	GOMAXPROCS(1)
44	TestSemaHandoff(t)
45}
46
47func TestSemaHandoff2(t *testing.T) {
48	if GOMAXPROCS(-1) <= 2 {
49		t.Skip("GOMAXPROCS <= 2")
50	}
51	defer GOMAXPROCS(GOMAXPROCS(-1))
52	GOMAXPROCS(2)
53	TestSemaHandoff(t)
54}
55
56func testSemaHandoff() bool {
57	var sema, res uint32
58	done := make(chan struct{})
59
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++ {
65		go func() {
66			for {
67				select {
68				case <-done:
69					return
70				default:
71				}
72				Gosched()
73			}
74		}()
75	}
76
77	go func() {
78		Semacquire(&sema)
79		atomic.CompareAndSwapUint32(&res, 0, 1)
80
81		Semrelease1(&sema, true, 0)
82		close(done)
83	}()
84	for SemNwait(&sema) == 0 {
85		Gosched() // wait for goroutine to block in Semacquire
86	}
87
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)
93
94	<-done // wait for goroutines to finish to avoid data races
95
96	return res == 1 // did the waiter run first?
97}
98