douchu5131 2015-05-09 06:39
浏览 1
已采纳

Golang-为什么发生这种比赛状况?

package main
import "fmt"

var quit chan int
var glo int

func test() {
    fmt.Println(glo)
}

func main() {
    glo = 0
    n := 10000
    quit = make(chan int, n)
    go test()
    for {
        quit <- 1
        glo++
    }
}

Situation:

The above program outputs 10000. But when I assign a bigger number to n (e.g. n := 1000000), the output will be a random number less than n.

I haven't called runtime.GOMAXPROCS(), so these two goroutines can't run in parallel. Executing go run -race to detect race conditions, ends up without any warnings.

Question:

Why does this race condition occur?

  • 写回答

1条回答 默认 最新

  • dpj997991 2015-05-09 07:08
    关注

    As there is no synchronisation between the main and test goroutines, you don't know at what point the fmt.Println call in test will happen.

    When running with GOMAXPROCS = 1, the answer will essentially depend on when the scheduler decides to stop executing main and switch to test. The send operation within the loop is one point where the scheduler can switch over to another goroutine, so with enough iterations of the loop you'd expect test to get a chance to execute at some point. It isn't necessarily going to switch at the same iteration every run leading to the variation in results.

    As for catching this with the race detector, it successfully catches the problem for me:

    $ go run -race test.go
    ==================
    WARNING: DATA RACE
    Read by goroutine 5:
      main.test()
          /../test.go:8 +0x6e
    
    Previous write by main goroutine:
      main.main()
          /.../test.go:18 +0xfe
    
    Goroutine 5 (running) created at:
      main.main()
          /.../test.go:15 +0x8f
    ==================
    ...
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 许可证msc licensing软件报错显示已有相同版本软件,但是下一步显示无法读取日志目录。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加
  • ¥15 用ns3仿真出5G核心网网元