Skip to content

Instantly share code, notes, and snippets.

@wrfly
Created October 8, 2018 08:43
Show Gist options
  • Save wrfly/079ee8472952d5057ae333c5589c98c4 to your computer and use it in GitHub Desktop.
Save wrfly/079ee8472952d5057ae333c5589c98c4 to your computer and use it in GitHub Desktop.
golang test race (pointer is not safe neither)
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