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 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)