是什么导致此数据竞赛?

时间:2019-01-08 11:02:53

标签: go atomic data-race

为什么此代码会导致数据争用? 我已经使用了原子添加。

package main

import (
    "sync/atomic"
    "time"
)

var a int64

func main() {
    for {
        if a < 100 {
            atomic.AddInt64(&a, 1)
            go run()
        }
    }
}

func run() {
    <-time.After(5 * time.Second)
    atomic.AddInt64(&a, -1)
}

我使用此代码运行命令go run --race并获取:

==================
WARNING: DATA RACE
Write at 0x000001150f30 by goroutine 8:
  sync/atomic.AddInt64()
      /usr/local/Cellar/go/1.11.2/libexec/src/runtime/race_amd64.s:276 +0xb
  main.run()
      /Users/flask/test.go:22 +0x6d

Previous read at 0x000001150f30 by main goroutine:
  main.main()
      /Users/flask/test.go:12 +0x3a

Goroutine 8 (running) created at:
  main.main()
      /Users/flask/test.go:15 +0x75
==================

您能帮我解释一下吗? 以及如何解决此警告? 谢谢!

1 个答案:

答案 0 :(得分:2)

您没有在访问变量的 all 地方使用atomic软件包。所有访问都必须同步到同时从多个goroutine中访问的变量,包括 reads

for {
    if value := atomic.LoadInt64(&a); value < 100 {
        atomic.AddInt64(&a, 1)
        go run()
    }
}

有了这个改变,比赛条件就消失了。

如果您只想检查值,甚至不需要将其存储在变量中,那么您可以简单地这样做:

for {
    if atomic.LoadInt64(&a) < 100 {
        atomic.AddInt64(&a, 1)
        go run()
    }
}