Skip to content

Instantly share code, notes, and snippets.

@meson10
Created April 4, 2015 03:10
Show Gist options
  • Save meson10/1f9f43befacd8c859501 to your computer and use it in GitHub Desktop.
Save meson10/1f9f43befacd8c859501 to your computer and use it in GitHub Desktop.
Race Condition
package main
import (
"log"
"time"
)
type Inner struct {
Count int
}
var cachedInner = map[string]*Inner{}
const KEY = "key"
func Get() *Inner {
var d *Inner
var ok bool
d, ok = cachedInner[KEY]
if !ok {
d = getInner()
}
return d
}
func getInner() *Inner {
log.Println("Generating Inner for Thread")
data := &Inner{}
cachedInner[KEY] = data
return data
}
func process() {
inner := Get()
inner.Count++
log.Println(inner.Count)
}
func main() {
log.SetFlags(log.Ldate | log.Ltime | log.Llongfile)
go process()
go process()
time.Sleep(2 * time.Second)
}
@meson10
Copy link
Author

meson10 commented Apr 4, 2015

Race Condition output:

piyush:~ [] $ go run -race /tmp/sample.go 
2015/04/04 08:38:21 /tmp/sample.go:29: Generating Inner for Thread
2015/04/04 08:38:21 /tmp/sample.go:38: 1
==================
WARNING: DATA RACE
Read by goroutine 6:
  runtime.mapaccess2_faststr()
      /usr/local/Cellar/go/1.4.2/libexec/src/runtime/hashmap_fast.go:281 +0x0
  main.Get()
      /tmp/sample.go:20 +0x7f
  main.process()
      /tmp/sample.go:36 +0x2c

Previous write by goroutine 5:
  runtime.mapassign1()
      /usr/local/Cellar/go/1.4.2/libexec/src/runtime/hashmap.go:383 +0x0
  main.getInner()
      /tmp/sample.go:31 +0x19f
  main.Get()
      /tmp/sample.go:22 +0xaf
  main.process()
      /tmp/sample.go:36 +0x2c

Goroutine 6 (running) created at:
  main.main()
      /tmp/sample.go:45 +0x55

Goroutine 5 (finished) created at:
  main.main()
      /tmp/sample.go:44 +0x44
==================
==================
WARNING: DATA RACE
Read by goroutine 6:
  main.process()
      /tmp/sample.go:37 +0x3f

Previous write by goroutine 5:
  main.getInner()
      /tmp/sample.go:30 +0x132
  main.Get()
      /tmp/sample.go:22 +0xaf
  main.process()
      /tmp/sample.go:36 +0x2c

Goroutine 6 (running) created at:
  main.main()
      /tmp/sample.go:45 +0x55

Goroutine 5 (finished) created at:
  main.main()
      /tmp/sample.go:44 +0x44
==================
2015/04/04 08:38:21 /tmp/sample.go:38: 2
^Cexit status 2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment