Skip to content

Instantly share code, notes, and snippets.

@calvinxiao
Created June 28, 2021 02:03
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 calvinxiao/c7ce2f4a75dd06a2ce1a3edf2139ac22 to your computer and use it in GitHub Desktop.
Save calvinxiao/c7ce2f4a75dd06a2ce1a3edf2139ac22 to your computer and use it in GitHub Desktop.
Go And Weak Memory Ordering
package main
import (
"log"
"math/rand"
)
//import "runtime"
var x, y, r1, r2 int
var ch1 = make(chan int)
var ch2 = make(chan int)
func run1() {
for {
<-ch1
for {
if rand.Int31()%8 == 0 {
break
}
}
x = 1
r1 = y
ch1 <- 1
}
}
func run2() {
for {
<-ch2
for {
if rand.Int31()%8 == 0 {
break
}
}
y = 1
r2 = x
ch2 <- 1
}
}
func main() {
go run1()
go run2()
detected := 0
for i := 1; ; i++ {
x = 0
y = 0
ch1 <- 1
ch2 <- 1
<-ch1
<-ch2
if r1 == 0 && r2 == 0 {
detected++
log.Printf("%d reordered detected, runc: %d", detected, i)
}
}
}
/*
# ./a
2021/06/28 02:02:35 1 reordered detected, runc: 8507500
2021/06/28 02:02:35 2 reordered detected, runc: 8523412
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment