dpchen2004 2019-05-23 11:19
浏览 76
已采纳

Golang并发写入变量-为什么此代码有效?

I'm learning concurrency-related issues in Golang. I wrote some code:

package main

import (
    "fmt"
    "time"
)

func incr(num *int) {
    *num = *num + 1

}

func main() {
    var a = 0

    for i := 0; i < 50; i++ {
        go incr(&a)
    }

    incr(&a)

    time.Sleep(1 * time.Second)
    fmt.Println(a)
}

The result of this code is: 51

In this code I've declared a variable which I'm increasing in 50 running goroutines. What I've read and unsterstood this code should fail because multiple goroutines are writing to same memory address. In this case I should add sync.Mutex lock in order to fix that.

Code is available in the playground: https://play.golang.org/p/Tba9pfpxaHY

Could You explain what is really happening in this program?

  • 写回答

1条回答 默认 最新

  • dongxi1879 2019-05-23 11:34
    关注

    Guess what? I ran your app and I get varying outputs: sometimes 49, sometimes 48, sometimes 50 (and sometimes 51).

    If you run your app with the race detector enabled (go run -race play.go), it tells you have data races:

    ==================
    WARNING: DATA RACE
    Read at 0x00c00009a010 by goroutine 7:
      main.incr()
          /home/icza/gows/src/play/play.go:9 +0x3a
    
    Previous write at 0x00c00009a010 by goroutine 6:
      main.incr()
          /home/icza/gows/src/play/play.go:9 +0x50
    
    Goroutine 7 (running) created at:
      main.main()
          /home/icza/gows/src/play/play.go:17 +0x83
    
    Goroutine 6 (finished) created at:
      main.main()
          /home/icza/gows/src/play/play.go:17 +0x83
    ==================
    

    When you have data races, the behavior of your app is undefined. "Seemingly working sometimes" also fits into the "undefined" behavior, but undefined also means it can do anything else too.

    See related questions:

    Assign a map to another map is safety in golang?

    Is it safe to read a function pointer concurrently without a lock?

    golang struct concurrent read and write without Lock is also running ok?

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

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!