Skip to content

Instantly share code, notes, and snippets.

@agocs
Last active August 29, 2015 13:57
Show Gist options
  • Save agocs/9379893 to your computer and use it in GitHub Desktop.
Save agocs/9379893 to your computer and use it in GitHub Desktop.
What happens when you create a data race in Go?
cagocs:examples christopheragocs$ go run shared_memory.go
I am a very global string.I have been to LondonI have been to France
I am a very global string.I have been to London
I am a very global string.I have been to LondonI have been to France
cagocs:examples christopheragocs$ go run -race shared_memory.go
==================
WARNING: DATA RACE
Write by goroutine 4:
main.writeToSomeString()
/Users/christopheragocs/personal/golangIntro/examples/shared_memory.go:26 +0x38
Previous write by goroutine 3:
main.writeToSomeString()
/Users/christopheragocs/personal/golangIntro/examples/shared_memory.go:26 +0x38
Goroutine 4 (running) created at:
main.main()
/Users/christopheragocs/personal/golangIntro/examples/shared_memory.go:15 +0xa7
Goroutine 3 (running) created at:
main.main()
/Users/christopheragocs/personal/golangIntro/examples/shared_memory.go:14 +0x79
==================
I am a very global string.I have been to LondonI have been to France
I am a very global string.I have been to London
I am a very global string.I have been to LondonI have been to France
Found 1 data race(s)
exit status 66
cagocs:examples christopheragocs$
package main
import (
"fmt"
"time"
)
var someString = "I am a very global string."
func main() {
stringChannel := make(chan string)
go writeToSomeString("I have been to London", stringChannel)
go writeToSomeString("I have been to France", stringChannel)
time.Sleep(1 << 24)
fmt.Println(someString)
fmt.Println(<-stringChannel)
fmt.Println(<-stringChannel)
}
func writeToSomeString(whatToWrite string, sc chan string) {
someString = someString + whatToWrite
sc <- someString
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment