douben7493 2019-07-31 20:21
浏览 83
已采纳

为什么种族探测器没有检测到这种种族状况?

I am currently learning the Go programming language and I am now experimenting with the atomic package.

In this example, I am spawning a number of Goroutines that all need to increment a package level variable. There are several methods to avoid race conditions but for now I want to solve this using the atomic package.

When running the following code on my Windows PC (go run main.go) the results are not what I expect them to be (I expect the final result to be 1000). The final number is somewhere between 900 and 1000. When running the code in the Go Playground the value is 1000.

Here is the code I am using: https://play.golang.org/p/8gW-AsKGzwq

var counter int64
var wg sync.WaitGroup

func main() {
    num := 1000
    wg.Add(num )
    for i := 0; i < num ; i++ {
        go func() {
            v := atomic.LoadInt64(&counter)
            v++
            atomic.StoreInt64(&counter, v)

            // atomic.AddInt64(&counter, 1)

            // fmt.Println(v)
            wg.Done()
        }()
    }
    wg.Wait()
    fmt.Println("final", counter)
}
go run main.go
final 931

go run main.go
final 960

go run main.go
final 918

I would have expected the race detector to give an error, but it doesn't:

go run -race main.go
final 1000

And it outputs the correct value (1000).

I am using go version go1.12.7 windows/amd64 (latest version at this moment)

My questions:

  • Why is the race detector not giving an error, but am I seeing different values when running the code without the race detector?
  • My theory why the Load/Store combination is not working is that the two atomic calls are not atomic as a whole. In this case I should be using the atomic.AddInt64 method, is that right?

Any help would be greatly appreciated :)

  • 写回答

1条回答 默认 最新

  • douzhe3516 2019-07-31 20:41
    关注

    There is nothing racy in your code, so that's why the race detector detects nothing. Your counter variable is always accessed via the atomic package from the launched goroutines and not directly.

    The reason why sometimes you get 1000 and sometimes less is due to the number of active threads that run goroutines: GOMAXPROCS. On the Go Playground it's 1, so at any time you have one active goroutine (so basically your app is executed sequentially, without any parallelism). And the current goroutine scheduler does not put goroutines to park arbitrarily.

    On your local machine you probably have a multicore CPU, and GOMAXPROCS defaults to the number of available logical CPUs, so GOMAXPROCS is greater than 1, so you have multiple goroutines running parallel (truly parallel, not just concurrent).

    See this fragment:

    v := atomic.LoadInt64(&counter)
    v++
    atomic.StoreInt64(&counter, v)
    

    You load counter's value and assign it to v, you increment v, and you store back the value of the incremented v. What happens if 2 parallel goroutines do this at the same time? Let's say both load the value 100. Both increment their local copy: 101. Both write back 101, even though it should be at 102.

    Yes, the proper way to increment counters atomically would be to use atomic.AddInt64() like this:

    for i := 0; i < num; i++ {
        go func() {
            atomic.AddInt64(&counter, 1)
            wg.Done()
        }()
    }
    

    This way you'll always get 1000, no matter what GOMAXPROCS is.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 我的R语言提示去除连锁不平衡时clump_data报错,图片以下所示,卡了好几天了,苦恼不知道如何解决,有人帮我看看怎么解决吗?
  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序