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?

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

报告相同问题?

悬赏问题

  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来