【发布时间】:2021-09-23 04:01:01
【问题描述】:
我是 Golang 的新手,我正在尝试理解 goroutines。 这是我从https://www.golangprograms.com/goroutines.html 得到的一段代码。
package main
import (
"fmt"
"runtime"
"sync"
"sync/atomic"
)
var (
counter int32 // counter is a variable incremented by all goroutines.
wg sync.WaitGroup // wg is used to wait for the program to finish.
)
func main() {
wg.Add(3) // Add a count of two, one for each goroutine.
go increment("Python")
go increment("Java")
go increment("Golang")
wg.Wait() // Wait for the goroutines to finish.
fmt.Println("Counter:", counter)
}
func increment(name string) {
defer wg.Done() // Schedule the call to Done to tell main we are done.
for range name {
fmt.Println("name:", name)
fmt.Println("Counter in range:", counter)
atomic.AddInt32(&counter, 1)
runtime.Gosched() // Yield the thread and be placed back in queue.
}
}
输出:
name: Golang
Counter in range: 0
name: Java
Counter in range: 1
name: Golang
Counter in range: 2
name: Golang
Counter in range: 3
name: Java
Counter in range: 4
name: Golang
Counter in range: 5
name: Python
Counter in range: 6
name: Java
Counter in range: 7
name: Golang
Counter in range: 8
name: Java
Counter in range: 9
name: Golang
Counter in range: 10
name: Python
Counter in range: 11
name: Python
Counter in range: 12
name: Python
Counter in range: 13
name: Python
Counter in range: 14
name: Python
Counter in range: 15
Counter: 16
我无法理解为什么输出是 16。即使我们只添加了 3 个 goroutine。不应该是3吗?
谁能解释一下?
谢谢。
【问题讨论】:
标签: go atomic race-condition goroutine