Source file src/runtime/runtime_test.go

     1  // Copyright 2012 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  
     5  package runtime_test
     6  
     7  import (
     8  	"flag"
     9  	"internal/asan"
    10  	"internal/cpu"
    11  	"internal/msan"
    12  	"internal/race"
    13  	"internal/runtime/atomic"
    14  	"internal/testenv"
    15  	"io"
    16  	"math/bits"
    17  	. "runtime"
    18  	"runtime/debug"
    19  	"slices"
    20  	"strings"
    21  	"sync"
    22  	"testing"
    23  	"time"
    24  	"unsafe"
    25  )
    26  
    27  // flagQuick is set by the -quick option to skip some relatively slow tests.
    28  // This is used by the cmd/dist test runtime:cpu124.
    29  // The cmd/dist test passes both -test.short and -quick;
    30  // there are tests that only check testing.Short, and those tests will
    31  // not be skipped if only -quick is used.
    32  var flagQuick = flag.Bool("quick", false, "skip slow tests, for cmd/dist test runtime:cpu124")
    33  
    34  func init() {
    35  	// We're testing the runtime, so make tracebacks show things
    36  	// in the runtime. This only raises the level, so it won't
    37  	// override GOTRACEBACK=crash from the user.
    38  	SetTracebackEnv("system")
    39  }
    40  
    41  var errf error
    42  
    43  func errfn() error {
    44  	return errf
    45  }
    46  
    47  func errfn1() error {
    48  	return io.EOF
    49  }
    50  
    51  func BenchmarkIfaceCmp100(b *testing.B) {
    52  	for i := 0; i < b.N; i++ {
    53  		for j := 0; j < 100; j++ {
    54  			if errfn() == io.EOF {
    55  				b.Fatal("bad comparison")
    56  			}
    57  		}
    58  	}
    59  }
    60  
    61  func BenchmarkIfaceCmpNil100(b *testing.B) {
    62  	for i := 0; i < b.N; i++ {
    63  		for j := 0; j < 100; j++ {
    64  			if errfn1() == nil {
    65  				b.Fatal("bad comparison")
    66  			}
    67  		}
    68  	}
    69  }
    70  
    71  var efaceCmp1 any
    72  var efaceCmp2 any
    73  
    74  func BenchmarkEfaceCmpDiff(b *testing.B) {
    75  	x := 5
    76  	efaceCmp1 = &x
    77  	y := 6
    78  	efaceCmp2 = &y
    79  	for i := 0; i < b.N; i++ {
    80  		for j := 0; j < 100; j++ {
    81  			if efaceCmp1 == efaceCmp2 {
    82  				b.Fatal("bad comparison")
    83  			}
    84  		}
    85  	}
    86  }
    87  
    88  func BenchmarkEfaceCmpDiffIndirect(b *testing.B) {
    89  	efaceCmp1 = [2]int{1, 2}
    90  	efaceCmp2 = [2]int{1, 2}
    91  	for i := 0; i < b.N; i++ {
    92  		for j := 0; j < 100; j++ {
    93  			if efaceCmp1 != efaceCmp2 {
    94  				b.Fatal("bad comparison")
    95  			}
    96  		}
    97  	}
    98  }
    99  
   100  func BenchmarkDefer(b *testing.B) {
   101  	for i := 0; i < b.N; i++ {
   102  		defer1()
   103  	}
   104  }
   105  
   106  func defer1() {
   107  	defer func(x, y, z int) {
   108  		if recover() != nil || x != 1 || y != 2 || z != 3 {
   109  			panic("bad recover")
   110  		}
   111  	}(1, 2, 3)
   112  }
   113  
   114  func BenchmarkDefer10(b *testing.B) {
   115  	for i := 0; i < b.N/10; i++ {
   116  		defer2()
   117  	}
   118  }
   119  
   120  func defer2() {
   121  	for i := 0; i < 10; i++ {
   122  		defer func(x, y, z int) {
   123  			if recover() != nil || x != 1 || y != 2 || z != 3 {
   124  				panic("bad recover")
   125  			}
   126  		}(1, 2, 3)
   127  	}
   128  }
   129  
   130  func BenchmarkDeferMany(b *testing.B) {
   131  	for i := 0; i < b.N; i++ {
   132  		defer func(x, y, z int) {
   133  			if recover() != nil || x != 1 || y != 2 || z != 3 {
   134  				panic("bad recover")
   135  			}
   136  		}(1, 2, 3)
   137  	}
   138  }
   139  
   140  func BenchmarkPanicRecover(b *testing.B) {
   141  	for i := 0; i < b.N; i++ {
   142  		defer3()
   143  	}
   144  }
   145  
   146  func defer3() {
   147  	defer func(x, y, z int) {
   148  		if recover() == nil {
   149  			panic("failed recover")
   150  		}
   151  	}(1, 2, 3)
   152  	panic("hi")
   153  }
   154  
   155  // golang.org/issue/7063
   156  func TestStopCPUProfilingWithProfilerOff(t *testing.T) {
   157  	SetCPUProfileRate(0)
   158  }
   159  
   160  // Addresses to test for faulting behavior.
   161  // This is less a test of SetPanicOnFault and more a check that
   162  // the operating system and the runtime can process these faults
   163  // correctly. That is, we're indirectly testing that without SetPanicOnFault
   164  // these would manage to turn into ordinary crashes.
   165  // Note that these are truncated on 32-bit systems, so the bottom 32 bits
   166  // of the larger addresses must themselves be invalid addresses.
   167  // We might get unlucky and the OS might have mapped one of these
   168  // addresses, but probably not: they're all in the first page, very high
   169  // addresses that normally an OS would reserve for itself, or malformed
   170  // addresses. Even so, we might have to remove one or two on different
   171  // systems. We will see.
   172  
   173  var faultAddrs = []uint64{
   174  	// low addresses
   175  	0,
   176  	1,
   177  	0xfff,
   178  	// high (kernel) addresses
   179  	// or else malformed.
   180  	0xffffffffffffffff,
   181  	0xfffffffffffff001,
   182  	0xffffffffffff0001,
   183  	0xfffffffffff00001,
   184  	0xffffffffff000001,
   185  	0xfffffffff0000001,
   186  	0xffffffff00000001,
   187  	0xfffffff000000001,
   188  	0xffffff0000000001,
   189  	0xfffff00000000001,
   190  	0xffff000000000001,
   191  	0xfff0000000000001,
   192  	0xff00000000000001,
   193  	0xf000000000000001,
   194  	0x8000000000000001,
   195  }
   196  
   197  func TestSetPanicOnFault(t *testing.T) {
   198  	old := debug.SetPanicOnFault(true)
   199  	defer debug.SetPanicOnFault(old)
   200  
   201  	nfault := 0
   202  	for _, addr := range faultAddrs {
   203  		testSetPanicOnFault(t, uintptr(addr), &nfault)
   204  	}
   205  	if nfault == 0 {
   206  		t.Fatalf("none of the addresses faulted")
   207  	}
   208  }
   209  
   210  // testSetPanicOnFault tests one potentially faulting address.
   211  // It deliberately constructs and uses an invalid pointer,
   212  // so mark it as nocheckptr.
   213  //
   214  //go:nocheckptr
   215  func testSetPanicOnFault(t *testing.T, addr uintptr, nfault *int) {
   216  	if GOOS == "js" || GOOS == "wasip1" {
   217  		t.Skip(GOOS + " does not support catching faults")
   218  	}
   219  
   220  	defer func() {
   221  		if err := recover(); err != nil {
   222  			*nfault++
   223  		}
   224  	}()
   225  
   226  	// The read should fault, except that sometimes we hit
   227  	// addresses that have had C or kernel pages mapped there
   228  	// readable by user code. So just log the content.
   229  	// If no addresses fault, we'll fail the test.
   230  	v := *(*byte)(unsafe.Pointer(addr))
   231  	t.Logf("addr %#x: %#x\n", addr, v)
   232  }
   233  
   234  func eqstring_generic(s1, s2 string) bool {
   235  	if len(s1) != len(s2) {
   236  		return false
   237  	}
   238  	// optimization in assembly versions:
   239  	// if s1.str == s2.str { return true }
   240  	for i := 0; i < len(s1); i++ {
   241  		if s1[i] != s2[i] {
   242  			return false
   243  		}
   244  	}
   245  	return true
   246  }
   247  
   248  func TestEqString(t *testing.T) {
   249  	// This isn't really an exhaustive test of == on strings, it's
   250  	// just a convenient way of documenting (via eqstring_generic)
   251  	// what == does.
   252  	s := []string{
   253  		"",
   254  		"a",
   255  		"c",
   256  		"aaa",
   257  		"ccc",
   258  		"cccc"[:3], // same contents, different string
   259  		"1234567890",
   260  	}
   261  	for _, s1 := range s {
   262  		for _, s2 := range s {
   263  			x := s1 == s2
   264  			y := eqstring_generic(s1, s2)
   265  			if x != y {
   266  				t.Errorf(`("%s" == "%s") = %t, want %t`, s1, s2, x, y)
   267  			}
   268  		}
   269  	}
   270  }
   271  
   272  func TestTrailingZero(t *testing.T) {
   273  	// make sure we add padding for structs with trailing zero-sized fields
   274  	type T1 struct {
   275  		n int32
   276  		z [0]byte
   277  	}
   278  	if unsafe.Sizeof(T1{}) != 8 {
   279  		t.Errorf("sizeof(%#v)==%d, want 8", T1{}, unsafe.Sizeof(T1{}))
   280  	}
   281  	type T2 struct {
   282  		n int64
   283  		z struct{}
   284  	}
   285  	align := unsafe.Alignof(T2{})
   286  	wantT2 := (uintptr(9) + align - 1) &^ (align - 1)
   287  	if unsafe.Sizeof(T2{}) != wantT2 {
   288  		t.Errorf("sizeof(%#v)==%d, want %d", T2{}, unsafe.Sizeof(T2{}), wantT2)
   289  	}
   290  	type T3 struct {
   291  		n byte
   292  		z [4]struct{}
   293  	}
   294  	if unsafe.Sizeof(T3{}) != 2 {
   295  		t.Errorf("sizeof(%#v)==%d, want 2", T3{}, unsafe.Sizeof(T3{}))
   296  	}
   297  	// make sure padding can double for both zerosize and alignment
   298  	type T4 struct {
   299  		a int32
   300  		b int16
   301  		c int8
   302  		z struct{}
   303  	}
   304  	if unsafe.Sizeof(T4{}) != 8 {
   305  		t.Errorf("sizeof(%#v)==%d, want 8", T4{}, unsafe.Sizeof(T4{}))
   306  	}
   307  	// make sure we don't pad a zero-sized thing
   308  	type T5 struct {
   309  	}
   310  	if unsafe.Sizeof(T5{}) != 0 {
   311  		t.Errorf("sizeof(%#v)==%d, want 0", T5{}, unsafe.Sizeof(T5{}))
   312  	}
   313  }
   314  
   315  func TestAppendGrowthHeap(t *testing.T) {
   316  	var x []int64
   317  	check := func(want int) {
   318  		if cap(x) != want {
   319  			t.Errorf("len=%d, cap=%d, want cap=%d", len(x), cap(x), want)
   320  		}
   321  	}
   322  
   323  	check(0)
   324  	want := 1
   325  	for i := 1; i <= 100; i++ {
   326  		x = append(x, 1)
   327  		check(want)
   328  		if i&(i-1) == 0 {
   329  			want = 2 * i
   330  		}
   331  	}
   332  	Escape(&x[0]) // suppress stack-allocated backing store
   333  }
   334  
   335  func TestAppendGrowthStack(t *testing.T) {
   336  	if race.Enabled || asan.Enabled || msan.Enabled {
   337  		t.Skip("instrumentation breaks this optimization")
   338  	}
   339  	var x []int64
   340  	check := func(want int) {
   341  		if cap(x) != want {
   342  			t.Errorf("len=%d, cap=%d, want cap=%d", len(x), cap(x), want)
   343  		}
   344  	}
   345  
   346  	check(0)
   347  	want := 32 / 8 // 32 is the default for cmd/compile/internal/base.DebugFlags.VariableMakeThreshold
   348  	if testenv.OptimizationOff() {
   349  		want = 1
   350  	}
   351  	for i := 1; i <= 100; i++ {
   352  		x = append(x, 1)
   353  		check(want)
   354  		if i&(i-1) == 0 {
   355  			want = max(want, 2*i)
   356  		}
   357  	}
   358  }
   359  
   360  var One = []int64{1}
   361  
   362  func TestAppendSliceGrowth(t *testing.T) {
   363  	var x []int64
   364  	check := func(want int) {
   365  		if cap(x) != want {
   366  			t.Errorf("len=%d, cap=%d, want cap=%d", len(x), cap(x), want)
   367  		}
   368  	}
   369  
   370  	check(0)
   371  	want := 1
   372  	for i := 1; i <= 100; i++ {
   373  		x = append(x, One...)
   374  		check(want)
   375  		if i&(i-1) == 0 {
   376  			want = 2 * i
   377  		}
   378  	}
   379  }
   380  
   381  func TestGoroutineProfileTrivial(t *testing.T) {
   382  	// Calling GoroutineProfile twice in a row should find the same number of goroutines,
   383  	// but it's possible there are goroutines just about to exit, so we might end up
   384  	// with fewer in the second call. Try a few times; it should converge once those
   385  	// zombies are gone.
   386  	for i := 0; ; i++ {
   387  		n1, ok := GoroutineProfile(nil) // should fail, there's at least 1 goroutine
   388  		if n1 < 1 || ok {
   389  			t.Fatalf("GoroutineProfile(nil) = %d, %v, want >0, false", n1, ok)
   390  		}
   391  		n2, ok := GoroutineProfile(make([]StackRecord, n1))
   392  		if n2 == n1 && ok {
   393  			break
   394  		}
   395  		t.Logf("GoroutineProfile(%d) = %d, %v, want %d, true", n1, n2, ok, n1)
   396  		if i >= 10 {
   397  			t.Fatalf("GoroutineProfile not converging")
   398  		}
   399  	}
   400  }
   401  
   402  func BenchmarkGoroutineProfile(b *testing.B) {
   403  	run := func(fn func() bool) func(b *testing.B) {
   404  		runOne := func(b *testing.B) {
   405  			latencies := make([]time.Duration, 0, b.N)
   406  
   407  			b.ResetTimer()
   408  			for i := 0; i < b.N; i++ {
   409  				start := time.Now()
   410  				ok := fn()
   411  				if !ok {
   412  					b.Fatal("goroutine profile failed")
   413  				}
   414  				latencies = append(latencies, time.Since(start))
   415  			}
   416  			b.StopTimer()
   417  
   418  			// Sort latencies then report percentiles.
   419  			slices.Sort(latencies)
   420  			b.ReportMetric(float64(latencies[len(latencies)*50/100]), "p50-ns")
   421  			b.ReportMetric(float64(latencies[len(latencies)*90/100]), "p90-ns")
   422  			b.ReportMetric(float64(latencies[len(latencies)*99/100]), "p99-ns")
   423  		}
   424  		return func(b *testing.B) {
   425  			b.Run("idle", runOne)
   426  
   427  			b.Run("loaded", func(b *testing.B) {
   428  				stop := applyGCLoad(b)
   429  				runOne(b)
   430  				// Make sure to stop the timer before we wait! The load created above
   431  				// is very heavy-weight and not easy to stop, so we could end up
   432  				// confusing the benchmarking framework for small b.N.
   433  				b.StopTimer()
   434  				stop()
   435  			})
   436  		}
   437  	}
   438  
   439  	// Measure the cost of counting goroutines
   440  	b.Run("small-nil", run(func() bool {
   441  		GoroutineProfile(nil)
   442  		return true
   443  	}))
   444  
   445  	// Measure the cost with a small set of goroutines
   446  	n := NumGoroutine()
   447  	p := make([]StackRecord, 2*n+2*GOMAXPROCS(0))
   448  	b.Run("small", run(func() bool {
   449  		_, ok := GoroutineProfile(p)
   450  		return ok
   451  	}))
   452  
   453  	// Measure the cost with a large set of goroutines
   454  	ch := make(chan int)
   455  	var ready, done sync.WaitGroup
   456  	for i := 0; i < 5000; i++ {
   457  		ready.Add(1)
   458  		done.Add(1)
   459  		go func() { ready.Done(); <-ch; done.Done() }()
   460  	}
   461  	ready.Wait()
   462  
   463  	// Count goroutines with a large allgs list
   464  	b.Run("large-nil", run(func() bool {
   465  		GoroutineProfile(nil)
   466  		return true
   467  	}))
   468  
   469  	n = NumGoroutine()
   470  	p = make([]StackRecord, 2*n+2*GOMAXPROCS(0))
   471  	b.Run("large", run(func() bool {
   472  		_, ok := GoroutineProfile(p)
   473  		return ok
   474  	}))
   475  
   476  	close(ch)
   477  	done.Wait()
   478  
   479  	// Count goroutines with a large (but unused) allgs list
   480  	b.Run("sparse-nil", run(func() bool {
   481  		GoroutineProfile(nil)
   482  		return true
   483  	}))
   484  
   485  	// Measure the cost of a large (but unused) allgs list
   486  	n = NumGoroutine()
   487  	p = make([]StackRecord, 2*n+2*GOMAXPROCS(0))
   488  	b.Run("sparse", run(func() bool {
   489  		_, ok := GoroutineProfile(p)
   490  		return ok
   491  	}))
   492  }
   493  
   494  func TestVersion(t *testing.T) {
   495  	// Test that version does not contain \r or \n.
   496  	vers := Version()
   497  	if strings.Contains(vers, "\r") || strings.Contains(vers, "\n") {
   498  		t.Fatalf("cr/nl in version: %q", vers)
   499  	}
   500  }
   501  
   502  func BenchmarkProcYield(b *testing.B) {
   503  	benchN := func(n uint32) func(*testing.B) {
   504  		return func(b *testing.B) {
   505  			for i := 0; i < b.N; i++ {
   506  				ProcYield(n)
   507  			}
   508  		}
   509  	}
   510  
   511  	b.Run("1", benchN(1))
   512  	b.Run("10", benchN(10))
   513  	b.Run("30", benchN(30)) // active_spin_cnt in lock_sema.go and lock_futex.go
   514  	b.Run("100", benchN(100))
   515  	b.Run("1000", benchN(1000))
   516  }
   517  
   518  func BenchmarkOSYield(b *testing.B) {
   519  	for i := 0; i < b.N; i++ {
   520  		OSYield()
   521  	}
   522  }
   523  
   524  func BenchmarkUsleep(b *testing.B) {
   525  	benchN := func(n uint32) func(*testing.B) {
   526  		return func(b *testing.B) {
   527  			for b.Loop() {
   528  				Usleep(n)
   529  			}
   530  		}
   531  	}
   532  
   533  	b.Run("1", benchN(1))           // darwin osyield
   534  	b.Run("3", benchN(3))           // runqgrab
   535  	b.Run("20", benchN(20))         // sysmon min
   536  	b.Run("10000", benchN(10*1000)) // sysmon max
   537  }
   538  
   539  func BenchmarkStealRunnextSleep(b *testing.B) {
   540  	benchN := func(ns int64) func(*testing.B) {
   541  		return func(b *testing.B) {
   542  			for b.Loop() {
   543  				StealRunnextSleep(ns)
   544  			}
   545  		}
   546  	}
   547  
   548  	b.Run("3us", benchN(3000))
   549  }
   550  
   551  func BenchmarkNoteTSleep(b *testing.B) {
   552  	benchN := func(ns int64, fn func(n *Note, ns int64) bool) func(*testing.B) {
   553  		return func(b *testing.B) {
   554  			n := new(Note)
   555  			for b.Loop() {
   556  				NoteClear(n)
   557  				woke := fn(n, ns)
   558  				if woke {
   559  					b.Fatal("something woke note; we expected timeout")
   560  				}
   561  			}
   562  		}
   563  	}
   564  
   565  	b.Run("g0-100us", benchN(100*1000, NoteTSleepG0)) // stopTheWorldWithSema, forEachPInternal
   566  	b.Run("g-100us", benchN(100*1000, NoteTSleepG))
   567  }
   568  
   569  func BenchmarkMutexContention(b *testing.B) {
   570  	// Measure throughput of a single mutex with all threads contending
   571  	//
   572  	// Share a single counter across all threads. Progress from any thread is
   573  	// progress for the benchmark as a whole. We don't measure or give points
   574  	// for fairness here, arbitrary delay to any given thread's progress is
   575  	// invisible and allowed.
   576  	//
   577  	// The cache line that holds the count value will need to move between
   578  	// processors, but not as often as the cache line that holds the mutex. The
   579  	// mutex protects access to the count value, which limits contention on that
   580  	// cache line. This is a simple design, but it helps to make the behavior of
   581  	// the benchmark clear. Most real uses of mutex will protect some number of
   582  	// cache lines anyway.
   583  
   584  	var state struct {
   585  		_     cpu.CacheLinePad
   586  		lock  Mutex
   587  		_     cpu.CacheLinePad
   588  		count atomic.Int64
   589  		_     cpu.CacheLinePad
   590  	}
   591  
   592  	procs := GOMAXPROCS(0)
   593  	var wg sync.WaitGroup
   594  	for range procs {
   595  		wg.Add(1)
   596  		go func() {
   597  			defer wg.Done()
   598  			for {
   599  				Lock(&state.lock)
   600  				ours := state.count.Add(1)
   601  				Unlock(&state.lock)
   602  				if ours >= int64(b.N) {
   603  					return
   604  				}
   605  			}
   606  		}()
   607  	}
   608  	wg.Wait()
   609  }
   610  
   611  func BenchmarkMutexCapture(b *testing.B) {
   612  
   613  	// Measure mutex fairness.
   614  	//
   615  	// Have several threads contend for a single mutex value. Measure how
   616  	// effectively a single thread is able to capture the lock and report the
   617  	// duration of those "streak" events. Measure how long other individual
   618  	// threads need to wait between their turns with the lock. Report the
   619  	// duration of those "starve" events.
   620  	//
   621  	// Report in terms of wall clock time (assuming a constant time per
   622  	// lock/unlock pair) rather than number of locks/unlocks. This keeps
   623  	// timekeeping overhead out of the critical path, and avoids giving an
   624  	// advantage to lock/unlock implementations that take less time per
   625  	// operation.
   626  
   627  	var state struct {
   628  		_     cpu.CacheLinePad
   629  		lock  Mutex
   630  		_     cpu.CacheLinePad
   631  		count atomic.Int64
   632  		_     cpu.CacheLinePad
   633  	}
   634  
   635  	procs := GOMAXPROCS(0)
   636  	var wg sync.WaitGroup
   637  	histograms := make(chan [2][65]int)
   638  	for range procs {
   639  		wg.Add(1)
   640  		go func() {
   641  			var (
   642  				prev      int64
   643  				streak    int64
   644  				histogram [2][65]int
   645  			)
   646  			for {
   647  				Lock(&state.lock)
   648  				ours := state.count.Add(1)
   649  				Unlock(&state.lock)
   650  				delta := ours - prev - 1
   651  				prev = ours
   652  				if delta == 0 {
   653  					streak++
   654  				} else {
   655  					histogram[0][bits.LeadingZeros64(uint64(streak))]++
   656  					histogram[1][bits.LeadingZeros64(uint64(delta))]++
   657  					streak = 1
   658  				}
   659  				if ours >= int64(b.N) {
   660  					wg.Done()
   661  					if delta == 0 {
   662  						histogram[0][bits.LeadingZeros64(uint64(streak))]++
   663  						histogram[1][bits.LeadingZeros64(uint64(delta))]++
   664  					}
   665  					histograms <- histogram
   666  					return
   667  				}
   668  			}
   669  		}()
   670  	}
   671  
   672  	wg.Wait()
   673  	b.StopTimer()
   674  
   675  	var histogram [2][65]int
   676  	for range procs {
   677  		h := <-histograms
   678  		for i := range h {
   679  			for j := range h[i] {
   680  				histogram[i][j] += h[i][j]
   681  			}
   682  		}
   683  	}
   684  
   685  	percentile := func(h [65]int, p float64) int {
   686  		sum := 0
   687  		for i, v := range h {
   688  			bound := uint64(1<<63) >> i
   689  			sum += int(bound) * v
   690  		}
   691  
   692  		// Imagine that the longest streak / starvation events were instead half
   693  		// as long but twice in number. (Note that we've pre-multiplied by the
   694  		// [lower] "bound" value.) Continue those splits until we meet the
   695  		// percentile target.
   696  		part := 0
   697  		for i, v := range h {
   698  			bound := uint64(1<<63) >> i
   699  			part += int(bound) * v
   700  			// have we trimmed off enough at the head to dip below the percentile goal
   701  			if float64(sum-part) < float64(sum)*p {
   702  				return int(bound)
   703  			}
   704  		}
   705  
   706  		return 0
   707  	}
   708  
   709  	perOp := float64(b.Elapsed().Nanoseconds()) / float64(b.N)
   710  	b.ReportMetric(perOp*float64(percentile(histogram[0], 1.0)), "ns/streak-p100")
   711  	b.ReportMetric(perOp*float64(percentile(histogram[0], 0.9)), "ns/streak-p90")
   712  	b.ReportMetric(perOp*float64(percentile(histogram[1], 1.0)), "ns/starve-p100")
   713  	b.ReportMetric(perOp*float64(percentile(histogram[1], 0.9)), "ns/starve-p90")
   714  }
   715  
   716  func BenchmarkMutexHandoff(b *testing.B) {
   717  	testcase := func(delay func(l *Mutex)) func(b *testing.B) {
   718  		return func(b *testing.B) {
   719  			if workers := 2; GOMAXPROCS(0) < workers {
   720  				b.Skipf("requires GOMAXPROCS >= %d", workers)
   721  			}
   722  
   723  			// Measure latency of mutex handoff between threads.
   724  			//
   725  			// Hand off a runtime.mutex between two threads, one running a
   726  			// "coordinator" goroutine and the other running a "worker"
   727  			// goroutine. We don't override the runtime's typical
   728  			// goroutine/thread mapping behavior.
   729  			//
   730  			// Measure the latency, starting when the coordinator enters a call
   731  			// to runtime.unlock and ending when the worker's call to
   732  			// runtime.lock returns. The benchmark can specify a "delay"
   733  			// function to simulate the length of the mutex-holder's critical
   734  			// section, including to arrange for the worker's thread to be in
   735  			// either the "spinning" or "sleeping" portions of the runtime.lock2
   736  			// implementation. Measurement starts after any such "delay".
   737  			//
   738  			// The two threads' goroutines communicate their current position to
   739  			// each other in a non-blocking way via the "turn" state.
   740  
   741  			var state struct {
   742  				_    cpu.CacheLinePad
   743  				lock Mutex
   744  				_    cpu.CacheLinePad
   745  				turn atomic.Int64
   746  				_    cpu.CacheLinePad
   747  			}
   748  
   749  			var delta atomic.Int64
   750  			var wg sync.WaitGroup
   751  
   752  			// coordinator:
   753  			//  - acquire the mutex
   754  			//  - set the turn to 2 mod 4, instructing the worker to begin its Lock call
   755  			//  - wait until the mutex is contended
   756  			//  - wait a bit more so the worker can commit to its sleep
   757  			//  - release the mutex and wait for it to be our turn (0 mod 4) again
   758  			wg.Add(1)
   759  			go func() {
   760  				defer wg.Done()
   761  				var t int64
   762  				for range b.N {
   763  					Lock(&state.lock)
   764  					state.turn.Add(2)
   765  					delay(&state.lock)
   766  					t -= Nanotime() // start the timer
   767  					Unlock(&state.lock)
   768  					for state.turn.Load()&0x2 != 0 {
   769  					}
   770  				}
   771  				state.turn.Add(1)
   772  				delta.Add(t)
   773  			}()
   774  
   775  			// worker:
   776  			//  - wait until its our turn (2 mod 4)
   777  			//  - acquire and release the mutex
   778  			//  - switch the turn counter back to the coordinator (0 mod 4)
   779  			wg.Add(1)
   780  			go func() {
   781  				defer wg.Done()
   782  				var t int64
   783  				for {
   784  					switch state.turn.Load() & 0x3 {
   785  					case 0:
   786  					case 1, 3:
   787  						delta.Add(t)
   788  						return
   789  					case 2:
   790  						Lock(&state.lock)
   791  						t += Nanotime() // stop the timer
   792  						Unlock(&state.lock)
   793  						state.turn.Add(2)
   794  					}
   795  				}
   796  			}()
   797  
   798  			wg.Wait()
   799  			b.ReportMetric(float64(delta.Load())/float64(b.N), "ns/op")
   800  		}
   801  	}
   802  
   803  	b.Run("Solo", func(b *testing.B) {
   804  		var lock Mutex
   805  		for range b.N {
   806  			Lock(&lock)
   807  			Unlock(&lock)
   808  		}
   809  	})
   810  
   811  	b.Run("FastPingPong", testcase(func(l *Mutex) {}))
   812  	b.Run("SlowPingPong", testcase(func(l *Mutex) {
   813  		// Wait for the worker to stop spinning and prepare to sleep
   814  		for !MutexContended(l) {
   815  		}
   816  		// Wait a bit longer so the OS can finish committing the worker to its
   817  		// sleep. Balance consistency against getting enough iterations.
   818  		const extraNs = 10e3
   819  		for t0 := Nanotime(); Nanotime()-t0 < extraNs; {
   820  		}
   821  	}))
   822  }
   823  

View as plain text