我刚刚学习互斥。我以为下面的程序总共会返回 1000,但我得到的结果各不相同,所以我认为我做错了什么......
package main
import (
"fmt"
"sync"
)
var total int
var locker sync.RWMutex
func add() {
for x := 1; x <= 100; x++ {
locker.Lock()
total += 1
locker.Unlock()
}
}
func main() {
for x := 1; x <= 10; x++ {
go add()
}
fmt.Printf("Total is %v\n", total)
}
最佳答案
Main 函数在 gorutines 完成它们的工作之前返回,你应该添加 sync.WaitGroup
,这段代码如你所料:https://play.golang.com/p/_OfrZae0soB
package main
import (
"fmt"
"sync"
)
var total int
var locker sync.RWMutex
func add(wg *sync.WaitGroup) {
defer wg.Done()
for x := 1; x <= 100; x++ {
locker.Lock()
total += 1
locker.Unlock()
}
}
func main() {
var wg sync.WaitGroup
for x := 1; x <= 10; x++ {
wg.Add(1)
go add(&wg)
}
wg.Wait()
fmt.Printf("Total is %v\n", total)
}
关于go - Mutex 似乎没有正确锁定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49344303/