Skip to content

Instantly share code, notes, and snippets.

@cyfdecyf
Last active December 18, 2015 11:59
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 cyfdecyf/5779241 to your computer and use it in GitHub Desktop.
Save cyfdecyf/5779241 to your computer and use it in GitHub Desktop.
Test if Go's assignment is atomic
package main
import (
"fmt"
"runtime"
)
func main() {
var (
k string // do assignment and read to this variable
i = "hello"
j = "world there"
)
runtime.GOMAXPROCS(2)
done := false
go func() {
// assign k, see if this is atomic
for !done {
k = i
k = j
}
}()
// repeatedly read k
// if assignment is atomic, this loop will never end
// real world results:
// 1. crash: invalid memory address or nil pointer dereference
// 2. print "hello"
// 3. print "world"
for {
p := k
if p != "" && p != i && p != j { // crash on this line
fmt.Println(p)
done = true
break
}
}
return
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment