douruhu4282 2019-01-08 11:02
浏览 101
已采纳

是什么导致此数据竞赛?

Why does this code cause data race? I have already used atomic add.

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)
}

I run command go run --race with this code and get:

==================
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
==================

Could you help me explain this? And how to fix this warning? Thanks!

  • 写回答

1条回答 默认 最新

  • duankangzi766767 2019-01-08 11:07
    关注

    You didn't use the atomic package at all places where you accessed the variable. All access must be synchronized to variables that are accessed from multiple goroutines concurrently, including reads:

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

    With that change, the race condition goes away.

    If you just want to inspect the value, you don't even need to store it in a variable, so you may simply do:

    for {
        if atomic.LoadInt64(&a) < 100 {
            atomic.AddInt64(&a, 1)
            go run()
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?