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.

    点赞 评论

相关推荐 更多相似问题