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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?