dpp66953 2015-11-14 18:30
浏览 29
已采纳

为什么在go例程中增加共享int变量时会显示原子行为?

when I run the following code snippet below, it looks it always prints the value 20000000. It shows similar behavior when I create more go routines to increment the counter without lock. But shouldn't there exist some kind of race condition ? Thanks !

package main

import "fmt"

const (
N_INCREMENTS = 10000000
)

func main() {

var counter int = 0
donechan := make(chan bool)

go func(done chan<- bool) {
    for i := 0; i < N_INCREMENTS; i++ {
        counter++
    }
    done <- true
}(donechan)

for i := 0; i < N_INCREMENTS; i++ {
    counter++
}

_ = <-donechan

fmt.Println("Count: ", counter)
}
  • 写回答

1条回答 默认 最新

  • doutan1875 2015-11-14 18:44
    关注

    runtime.GOMAXPROCS(0) will report you the number of goroutines that can be run parallel. If the value is 1, you may not observe any "side effect" of not synchronizing the counter variable.

    If first at the beginning of your program you set it to 2:

    runtime.GOMAXPROCS(2)
    

    You will immediately see the effect:

    Count:  10319575
    

    If you want to have proof of the race condition, supply the -race argument. The output with -race:

    ==================
    WARNING: DATA RACE
    Read by goroutine 6:
      main.main.func1()
          V:/workspace/IczaGo/src/play/play.go:20 +0x48
    
    Previous write by main goroutine:
      main.main()
          V:/workspace/IczaGo/src/play/play.go:26 +0xef
    
    Goroutine 6 (running) created at:
      main.main()
          V:/workspace/IczaGo/src/play/play.go:23 +0xbc
    ==================
    

    (Note that the race detector only works with 64-bit Go distributions.)

    On the Go playground, GOMAXPROCS is 1 by default. This line will print the previous value and set it to 2:

    fmt.Println("Previous GOMAXPROCS:", runtime.GOMAXPROCS(2))
    

    Output (try it on the Go Playground):

    Previous GOMAXPROCS: 1
    Count:  12844130
    

    Also note that GOMAXPROCS is set to 1 in Go distributions prior to 1.5. Starting with 1.5 the default value of GOMAXPROCS is the number of CPU cores available on the machine running the program.

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

报告相同问题?

悬赏问题

  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 qgcomp混合物线性模型分析的代码出现错误:Model aliasing occurred
  • ¥100 已有python代码,要求做成可执行程序,程序设计内容不多
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助
  • ¥15 STM32控制MAX7219问题求解答