Yus*_*aan 2 concurrency loops go
这会打印 0。
但是当我在 for 循环中添加空的 fmt.Println() 时,它会打印非零值。任何想法为什么?
GOMAXPROCS=1 ./foo
0
Run Code Online (Sandbox Code Playgroud)
package main
import (
"log"
"os"
"time"
)
func main() {
var i uint64
t := time.AfterFunc(time.Second*1, func() {
log.Println(i)
os.Exit(0)
})
defer t.Stop()
for {
i++
}
}
Run Code Online (Sandbox Code Playgroud)
你有一个数据竞争:你在没有同步的情况下从多个 goroutine 访问同一个变量。结果是不确定的。使用适当的同步。
确实,您没有在代码中启动 goroutines,而是引用自time.AfterFunc()
:
AfterFunc 等待持续时间过去,然后在自己的 goroutine 中调用 f。
因此,您有main
goroutine 递增(写入)变量i
,并且您将有另一个 goroutine 执行您传递给time.AfterFunc()
它将 read的函数i
。
使用同步的示例:
var (
mu sync.Mutex
i uint64
)
t := time.AfterFunc(time.Second*1, func() {
mu.Lock()
log.Println(i)
mu.Unlock()
os.Exit(0)
})
defer t.Stop()
for {
mu.Lock()
i++
mu.Unlock()
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
92 次 |
最近记录: |