Skip to content

Instantly share code, notes, and snippets.

@ash2k
Created March 11, 2016 12:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ash2k/8c308a79874edd637fc1 to your computer and use it in GitHub Desktop.
Save ash2k/8c308a79874edd637fc1 to your computer and use it in GitHub Desktop.
An example of racy map access pattern
$ 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)
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