Last active
December 18, 2015 11:59
-
-
Save cyfdecyf/5779241 to your computer and use it in GitHub Desktop.
Test if Go's assignment is atomic
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 ( | |
"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