Created
April 4, 2015 03:10
-
-
Save meson10/1f9f43befacd8c859501 to your computer and use it in GitHub Desktop.
Race Condition
This file contains 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 ( | |
"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) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Race Condition output: