duanfu1942 2017-03-26 14:49 采纳率: 100%
浏览 38
已采纳

Golang中的并发

I have a question about concurrency in GoLang. Here is a sample code in GoLang

package main

import(
    "fmt"
    "time"
)

var m int
func add(i int){
    m++
}

func main() {
    m = 0
    for i:=0;i<100;i++{
        go add(i)
    }
    time.Sleep(time.Millisecond * 1000)
    fmt.Println(m)
}

When I execute it I always have the same result 100, even if I execute it several times.

If I do the same code in C (without mutex), sometimes I have different results.

And my question, I would like to know if GoLang implicitly manages access to a shared variable using an internal mechanism ?

Thank you.

  • 写回答

6条回答 默认 最新

  • douhezi2285 2017-03-26 15:10
    关注

    No. For example, using your program,

    $ go run -race dz00dz.go
    ==================
    WARNING: DATA RACE
    Read at 0x000000595200 by goroutine 7:
      main.add()
         /home/peter/gopath/src/dz00dz.go:11 +0x3d
    
    Previous write at 0x000000595200 by goroutine 6:
      main.add()
          /home/peter/gopath/src/dz00dz.go:11 +0x59
    
    Goroutine 7 (running) created at:
      main.main()
          /home/peter/gopath/src/dz00dz.go:17 +0x76
    
    Goroutine 6 (finished) created at:
      main.main()
          /home/peter/gopath/src/dz00dz.go:17 +0x76
    ==================
    100
    Found 1 data race(s)
    exit status 66
    

    References:

    Introducing the Go Race Detector

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器