Go 最简单的竞走条件示例?
我需要一个简单的围棋代码样本,它肯定会运行到比赛条件下的程序 有什么想法吗?原始问题: 我需要一个简单的围棋代码样本,它肯定会运行该程序 进入比赛状态Go 最简单的竞走条件示例?,go,memory,race-condition,Go,Memory,Race Condition,我需要一个简单的围棋代码样本,它肯定会运行到比赛条件下的程序 有什么想法吗?原始问题: 我需要一个简单的围棋代码样本,它肯定会运行该程序 进入比赛状态 比如说, racer.go: package main import ( "time" ) var count int func race() { count++ } func main() { go race() go race() time.Sleep(1 * time.Second) }
比如说,
racer.go
:
package main
import (
"time"
)
var count int
func race() {
count++
}
func main() {
go race()
go race()
time.Sleep(1 * time.Second)
}
输出:
$ go run -race racer.go
==================
WARNING: DATA RACE
Read at 0x00000052ccf8 by goroutine 6:
main.race()
/home/peter/gopath/src/racer.go:10 +0x3a
Previous write at 0x00000052ccf8 by goroutine 5:
main.race()
/home/peter/gopath/src/racer.go:10 +0x56
Goroutine 6 (running) created at:
main.main()
/home/peter/gopath/src/racer.go:15 +0x5a
Goroutine 5 (finished) created at:
main.main()
/home/peter/gopath/src/racer.go:14 +0x42
==================
Found 1 data race(s)
exit status 66
$
运行代码时使用:
go Run-race.go
有两个goroutine,它们在相同的值上运行。这就是竞赛条件的定义。为了确保它确实遇到了数据竞争(你不能真正保证它,但已经足够接近),让他们在无限循环中对值进行操作。请不要在发布答案后将你的问题编辑成其他内容。相反,问一个新问题。我已将您的编辑回滚到已答复的版本。谢谢,这正是我想要的。
package main
import (
"fmt"
)
func main() {
i := 0
// Run forever to make it to show race condition
for {
var x, y int
// Set x to 60
go func(v *int) {
*v = 60
}(&x)
// Set y to 3
go func(v *int) {
*v = 3
}(&y)
/*
A race condition is when multiple threads are trying to access and manipulate the same variable.
the code below is all accessing and changing the value.
Divide x (60) by y (3) and assign to z (42)...
Except if y is not assigned 3 before x is assigned 60,
y's initialized value of 0 is used,
Due to the uncertainty of the Goroutine scheduling mechanism, the results of the following program is unpredictable,
which causes a divide by zero exception.
*/
go func(v1 int, v2 int) {
fmt.Println(v1 / v2)
}(x, y)
i += 1
fmt.Printf("%d\n", i)
}
}