Created
October 8, 2018 08:43
-
-
Save wrfly/079ee8472952d5057ae333c5589c98c4 to your computer and use it in GitHub Desktop.
golang test race (pointer is not safe neither)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
// ➜ race go test -race -run TestNoRace . | |
// ok _/Users/shaun.fu/test/go/race 1.288s | |
// ➜ race go test -race -run TestRace . | |
import ( | |
"sync" | |
"testing" | |
) | |
func TestRace(t *testing.T) { | |
var x = &xx{ | |
n: 6, | |
} | |
go func() { | |
for { | |
if x.n == 0 { | |
panic("") | |
} | |
} | |
}() | |
for i := 1; i < 1e5; i++ { | |
x = &xx{ | |
n: i, | |
} | |
} | |
} | |
func TestNoRace(t *testing.T) { | |
var rw sync.RWMutex | |
var x = &xx{ | |
n: 6, | |
} | |
go func() { | |
for { | |
rw.RLock() | |
if x.n == 0 { | |
panic("") | |
} | |
rw.RUnlock() | |
} | |
}() | |
for i := 1; i < 1e5; i++ { | |
rw.Lock() | |
x = &xx{ | |
n: i, | |
} | |
rw.Unlock() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment