github.com/likebike/go--@v0.0.0-20190911215757-0bd925d16e96/go/src/runtime/race/testdata/mutex_test.go (about) 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 race_test 6 7 import ( 8 "sync" 9 "testing" 10 "time" 11 ) 12 13 func TestNoRaceMutex(t *testing.T) { 14 var mu sync.Mutex 15 var x int16 = 0 16 _ = x 17 ch := make(chan bool, 2) 18 go func() { 19 mu.Lock() 20 defer mu.Unlock() 21 x = 1 22 ch <- true 23 }() 24 go func() { 25 mu.Lock() 26 x = 2 27 mu.Unlock() 28 ch <- true 29 }() 30 <-ch 31 <-ch 32 } 33 34 func TestRaceMutex(t *testing.T) { 35 var mu sync.Mutex 36 var x int16 = 0 37 _ = x 38 ch := make(chan bool, 2) 39 go func() { 40 x = 1 41 mu.Lock() 42 defer mu.Unlock() 43 ch <- true 44 }() 45 go func() { 46 x = 2 47 mu.Lock() 48 mu.Unlock() 49 ch <- true 50 }() 51 <-ch 52 <-ch 53 } 54 55 func TestRaceMutex2(t *testing.T) { 56 var mu1 sync.Mutex 57 var mu2 sync.Mutex 58 var x int8 = 0 59 _ = x 60 ch := make(chan bool, 2) 61 go func() { 62 mu1.Lock() 63 defer mu1.Unlock() 64 x = 1 65 ch <- true 66 }() 67 go func() { 68 mu2.Lock() 69 x = 2 70 mu2.Unlock() 71 ch <- true 72 }() 73 <-ch 74 <-ch 75 } 76 77 func TestNoRaceMutexPureHappensBefore(t *testing.T) { 78 var mu sync.Mutex 79 var x int16 = 0 80 _ = x 81 ch := make(chan bool, 2) 82 go func() { 83 x = 1 84 mu.Lock() 85 mu.Unlock() 86 ch <- true 87 }() 88 go func() { 89 <-time.After(1e5) 90 mu.Lock() 91 mu.Unlock() 92 x = 1 93 ch <- true 94 }() 95 <-ch 96 <-ch 97 } 98 99 func TestNoRaceMutexSemaphore(t *testing.T) { 100 var mu sync.Mutex 101 ch := make(chan bool, 2) 102 x := 0 103 _ = x 104 mu.Lock() 105 go func() { 106 x = 1 107 mu.Unlock() 108 ch <- true 109 }() 110 go func() { 111 mu.Lock() 112 x = 2 113 mu.Unlock() 114 ch <- true 115 }() 116 <-ch 117 <-ch 118 } 119 120 // from doc/go_mem.html 121 func TestNoRaceMutexExampleFromHtml(t *testing.T) { 122 var l sync.Mutex 123 a := "" 124 125 l.Lock() 126 go func() { 127 a = "hello, world" 128 l.Unlock() 129 }() 130 l.Lock() 131 _ = a 132 } 133 134 func TestRaceMutexOverwrite(t *testing.T) { 135 c := make(chan bool, 1) 136 var mu sync.Mutex 137 go func() { 138 mu = sync.Mutex{} 139 c <- true 140 }() 141 mu.Lock() 142 <-c 143 }