我想让 X 个 goroutineCountValue使用并行性进行更新(numRoutines 与你拥有的 CPU 数量一样多)。
解决方案一:
func count(numRoutines int) (countValue int) {
var mu sync.Mutex
k := func(i int) {
mu.Lock()
defer mu.Unlock()
countValue += 5
}
for i := 0; i < numRoutines; i++ {
go k(i)
}
Run Code Online (Sandbox Code Playgroud)
它变成了数据竞争和返回的countValue = 0.
解决方案2:
func count(numRoutines int) (countValue int) {
k := func(i int, c chan int) {
c <- 5
}
c := make(chan int)
for i := 0; i < numRoutines; i++ { …Run Code Online (Sandbox Code Playgroud)