Created
March 11, 2016 12:01
-
-
Save ash2k/8c308a79874edd637fc1 to your computer and use it in GitHub Desktop.
An example of racy map access pattern
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
$ go build --race ./main.go | |
$ ./main | |
5 | |
================== | |
WARNING: DATA RACE | |
Read by goroutine 7: | |
runtime.mapaccess1_fast64() | |
/usr/local/Cellar/go/1.6/libexec/src/runtime/hashmap_fast.go:103 +0x0 | |
main.main.func2() | |
/Users/ash2k/sources/gotest2/main.go:18 +0x4e | |
Previous write by goroutine 6: | |
runtime.mapassign1() | |
/usr/local/Cellar/go/1.6/libexec/src/runtime/hashmap.go:429 +0x0 | |
main.main.func1() | |
/Users/ash2k/sources/gotest2/main.go:14 +0xa6 | |
Goroutine 7 (running) created at: | |
main.main() | |
/Users/ash2k/sources/gotest2/main.go:20 +0xe0 | |
Goroutine 6 (finished) created at: | |
main.main() | |
/Users/ash2k/sources/gotest2/main.go:16 +0xb5 | |
================== | |
0 | |
Found 1 data race(s) |
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 | |
import ( | |
"fmt" | |
"sync" | |
) | |
func main() { | |
var l sync.Mutex | |
x := make(map[int]int) | |
go func(z int) { | |
l.Lock() | |
defer l.Unlock() | |
x[z] = z | |
fmt.Println(z) | |
}(5) | |
go func(z int) { | |
v := x[z] // Read without proper locking | |
fmt.Println(v) | |
}(0) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment