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 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化