File tree Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change @@ -7,6 +7,47 @@ import (
77 "testing"
88)
99
10+ func HammerMutex (m * sync.Mutex , loops int , cdone chan bool ) {
11+ for i := 0 ; i < loops ; i ++ {
12+ if i % 3 == 0 {
13+ if m .TryLock () {
14+ m .Unlock ()
15+ }
16+ continue
17+ }
18+ m .Lock ()
19+ m .Unlock ()
20+ }
21+ cdone <- true
22+ }
23+
24+ func TestMutex (t * testing.T ) {
25+ if n := runtime .SetMutexProfileFraction (1 ); n != 0 {
26+ t .Logf ("got mutexrate %d expected 0" , n )
27+ }
28+ defer runtime .SetMutexProfileFraction (0 )
29+
30+ m := new (sync.Mutex )
31+
32+ m .Lock ()
33+ if m .TryLock () {
34+ t .Fatalf ("TryLock succeeded with mutex locked" )
35+ }
36+ m .Unlock ()
37+ if ! m .TryLock () {
38+ t .Fatalf ("TryLock failed with mutex unlocked" )
39+ }
40+ m .Unlock ()
41+
42+ c := make (chan bool )
43+ for i := 0 ; i < 10 ; i ++ {
44+ go HammerMutex (m , 1000 , c )
45+ }
46+ for i := 0 ; i < 10 ; i ++ {
47+ <- c
48+ }
49+ }
50+
1051// TestMutexUncontended tests locking and unlocking a Mutex that is not shared with any other goroutines.
1152func TestMutexUncontended (t * testing.T ) {
1253 var mu sync.Mutex
You can’t perform that action at this time.
0 commit comments