gpt4 book ai didi

go - Go中的竞争条件变化

转载 作者:IT王子 更新时间:2023-10-29 02:27:05 25 4
gpt4 key购买 nike

《Go in action》关于竞争条件的示例:

var (
counter int
wg sync.WaitGroup
)

func main() {
wg.Add(2)
go incCounter(1)
go incCounter(2)

wg.Wait()
fmt.Println("Final Counter:", counter)
}

func incCounter(id int) {
defer wg.Done()

for count := 0; count < 2; count++ {
value := counter
//1 fmt.Println("value=",value)
runtime.Gosched()

value++

counter = value
//2 fmt.Println("counter=",counter)
}
}

据说最后Final Counter应该是2,这里解释一下:“每个 goroutine 都会覆盖另一个 goroutine 的工作。这发生在 goroutine交换正在进行。每个 goroutine 都有自己的计数器变量副本,并且然后换出另一个 goroutine。当 goroutine 有时间再次执行时,counter 变量的值发生了变化,但 goroutine 并没有更新其副本。相反,它继续增加它拥有的副本并设置值回到计数器变量,替换另一个 goroutine 执行的工作。”

我猜是环境原因,我的机器用 go 1.10.3+win10 输出 4。我想知道这本书出版后 go 发生了什么变化?如果我取消注释标记 1,Final Counter 打印 2 或者如果我取消注释标记 2,则随机打印。为什么?

最佳答案

这本书错了。数据竞争的要点是结果是不确定的。

例如,Final Counter 可以是任何值。

package main

import (
"fmt"
"runtime"
"sync"
)

var (
counter int
wg sync.WaitGroup
)

func main() {
wg.Add(2)
go incCounter(1)
go incCounter(2)

wg.Wait()
fmt.Println("Final Counter:", counter)
}

func incCounter(id int) {
defer wg.Done()

for count := 0; count < 2; count++ {
value := counter
//1 fmt.Println("value=",value)
runtime.Gosched()

value++

counter = value
//2 fmt.Println("counter=",counter)
}
}

输出:

$ go version
go version devel +65fa2b615b Fri Aug 3 23:35:53 2018 +0000 linux/amd64
$ go run racer.go
Final Counter: 4
$ go run racer.go
Final Counter: 2
$ go run racer.go
Final Counter: 2
$ go run racer.go
Final Counter: 2
$ go run racer.go
Final Counter: 2
$ go run racer.go
Final Counter: 4
$ go run racer.go
Final Counter: 2
$ go run racer.go
Final Counter: 4
$ go run -race racer.go
==================
WARNING: DATA RACE
Read at 0x0000005e4600 by goroutine 7:
main.incCounter()
/home/peter/gopath/src/racer.go:27 +0x6f

Previous write at 0x0000005e4600 by goroutine 6:
main.incCounter()
/home/peter/gopath/src/racer.go:33 +0x90

Goroutine 7 (running) created at:
main.main()
/home/peter/gopath/src/racer.go:17 +0x89

Goroutine 6 (finished) created at:
main.main()
/home/peter/gopath/src/racer.go:16 +0x68
==================
Final Counter: 4
Found 1 data race(s)
exit status 66
$

关于go - Go中的竞争条件变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51683305/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com