-
-
Save calvinxiao/c7ce2f4a75dd06a2ce1a3edf2139ac22 to your computer and use it in GitHub Desktop.
Go And Weak Memory Ordering
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" | |
"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