Go 互斥锁似乎没有正确锁定
我只是在学习沉默。我原以为下面的程序将返回总共1000个,但我得到了不同的结果,所以我假设我做错了什么Go 互斥锁似乎没有正确锁定,go,Go,我只是在学习沉默。我原以为下面的程序将返回总共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()
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)
}
主程序包
进口(
“fmt”
“同步”
)
总整数
var locker sync.RWMutex
func add(){
对于x:=1;x在检查结果之前,您没有等待开始完成的任何goroutine。使用WaitGroup
等待所有goroutine完成。在检查结果之前,您没有等待开始完成的任何goroutine。使用WaitGroup
等待所有goroutine完成。 您有一个数据竞争。因此,结果是未定义的
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)
}
您有一个数据竞争。因此,结果是未定义的
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
,此代码按预期工作:
主程序包
进口(
“fmt”
“同步”
)
总整数
var locker sync.RWMutex
func add(wg*sync.WaitGroup){
推迟工作组完成()
对于x:=1;xMain函数在gorutines完成其工作之前返回,应添加sync.WaitGroup
,此代码按预期工作:
主程序包
进口(
“fmt”
“同步”
)
总整数
var locker sync.RWMutex
func add(wg*sync.WaitGroup){
推迟工作组完成()
对于x:=1;x太棒了。谢谢!太棒了。谢谢!我不知道-race选项…我会调查的。谢谢。我不知道-race选项…我会调查的。谢谢。我只给了另一个答案打勾,因为它显示了一个例子。谢谢。我只给了另一个答案打勾,因为它显示了一个例子。
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)
}