假设我有这个:
go func() {
for range time.Tick(1 * time.Millisecond) {
a, b = b, a
}
}()
Run Code Online (Sandbox Code Playgroud)
其他地方:
i := a // <-- Is this safe?
Run Code Online (Sandbox Code Playgroud)
对于这个问题,i与原始a或者相关的价值是不重要的b.唯一的问题是阅读a是否安全.也就是说,是否有可能a被nil部分分配,无效,未定义,......除了有效值之外的任何东西?
我试图让它失败,但到目前为止它总是成功(在我的Mac上).
在Go Go Memory Model文档中,我无法找到超出此引用的任何特定内容:
大于单个机器字的值的读取和写入表现为以未指定的顺序进行的多个机器字大小的操作.
这是否意味着单个机器字写入实际上是原子的?并且,如果是这样,函数指针写入Go单个机器字操作?
更新:这是一个正确同步的解决方案
I'm learning concurrency-related issues in Golang. I wrote some code:
package main
import (
"fmt"
"time"
)
func incr(num *int) {
*num = *num + 1
}
func main() {
var a = 0
for i := 0; i < 50; i++ {
go incr(&a)
}
incr(&a)
time.Sleep(1 * time.Second)
fmt.Println(a)
}
Run Code Online (Sandbox Code Playgroud)
The result of this code is: 51
In this code I've declared a variable which I'm increasing in 50 running goroutines. What I've read and unsterstood this code …