我对 GoLang 中的并发有疑问。这是 GoLang 中的示例代码
package main
import(
"fmt"
"time"
)
var m int
func add(i int){
m++
}
func main() {
m = 0
for i:=0;i<100;i++{
go add(i)
}
time.Sleep(time.Millisecond * 1000)
fmt.Println(m)
}
当我执行它时,我总是得到相同的结果 100,即使我执行了几次也是如此。
如果我在 C 中执行相同的代码(没有互斥量),有时我会得到不同的结果。
我的问题是,我想知道 GoLang 是否使用内部机制隐式管理对共享变量的访问?
谢谢。
最佳答案
没有。例如,使用您的程序,
$ go run -race dz00dz.go
==================
WARNING: DATA RACE
Read at 0x000000595200 by goroutine 7:
main.add()
/home/peter/gopath/src/dz00dz.go:11 +0x3d
Previous write at 0x000000595200 by goroutine 6:
main.add()
/home/peter/gopath/src/dz00dz.go:11 +0x59
Goroutine 7 (running) created at:
main.main()
/home/peter/gopath/src/dz00dz.go:17 +0x76
Goroutine 6 (finished) created at:
main.main()
/home/peter/gopath/src/dz00dz.go:17 +0x76
==================
100
Found 1 data race(s)
exit status 66
引用资料:
关于go - golang 中的并发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43030245/