为什么无限循环不增加整数?

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)

icz*_*cza 5

你有一个数据竞争:你在没有同步的情况下从多个 goroutine 访问同一个变量。结果是不确定的。使用适当的同步。

确实,您没有在代码中启动 goroutines,而是引用自time.AfterFunc()

AfterFunc 等待持续时间过去,然后在自己的 goroutine 中调用 f

因此,您有maingoroutine 递增(写入)变量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)

  • 再次强调:对于数据竞争,结果是不确定的。推理发生了什么以及为什么发生是没有意义的。仅当您没有数据竞争时。 (4认同)