gpt4 book ai didi

go - 如何修复 "one problem on race condition check which using go-build-race tools"?

转载 作者:IT王子 更新时间:2023-10-29 01:40:39 27 4
gpt4 key购买 nike

起初,我知道代码有一些竞争条件,所以我使用“go build -race”命令来检查它,我想看看结果如何显示,当我第一次运行时,它显示了第一个结果如下,然后再次运行显示第二个,它有两个不同的结果,我不知道为什么,有谁能告诉我原因,以及代码是如何执行的?,非常感谢很多。

源代码:

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
// switch goroutine
runtime.Gosched()
value++
counter = value
}
}

当我使用 go build -race 工具检查竞争条件时,它显示了两个不同的结果,如下所示:

一个结果:

==================
WARNING: DATA RACE
Write at 0x0000005fb2d0 by goroutine 7:
main.incCounter()
D:/Go/projects/hello-world/src/concurrency/list7/m.go:34 +0x97

Previous read at 0x0000005fb2d0 by goroutine 6:
main.incCounter()
D:/Go/projects/hello-world/src/concurrency/list7/m.go:30 +0x76

Goroutine 7 (running) created at:
main.main()
D:/Go/projects/hello-world/src/concurrency/list7/m.go:18 +0x90

Goroutine 6 (running) created at:
main.main()
D:/Go/projects/hello-world/src/concurrency/list7/m.go:17 +0x6f
==================
==================
WARNING: DATA RACE
Write at 0x0000005fb2d0 by goroutine 6:
main.incCounter()
D:/Go/projects/hello-world/src/concurrency/list7/m.go:34 +0x97

Previous write at 0x0000005fb2d0 by goroutine 7:
main.incCounter()
D:/Go/projects/hello-world/src/concurrency/list7/m.go:34 +0x97

Goroutine 6 (running) created at:
main.main()
D:/Go/projects/hello-world/src/concurrency/list7/m.go:17 +0x6f

Goroutine 7 (running) created at:
main.main()
D:/Go/projects/hello-world/src/concurrency/list7/m.go:18 +0x90
==================
Final Counter: 2
Found 2 data race(s)

第二个结果:

==================
WARNING: DATA RACE
Read at 0x0000005fb2d0 by goroutine 7:
main.incCounter()
D:/Go/projects/hello-world/src/concurrency/list7/m.go:30 +0x76

Previous write at 0x0000005fb2d0 by goroutine 6:
main.incCounter()
D:/Go/projects/hello-world/src/concurrency/list7/m.go:34 +0x97

Goroutine 7 (running) created at:
main.main()
D:/Go/projects/hello-world/src/concurrency/list7/m.go:18 +0x90

Goroutine 6 (finished) created at:
main.main()
D:/Go/projects/hello-world/src/concurrency/list7/m.go:17 +0x6f
==================
Final Counter: 4
Found 1 data race(s)

它们是两个不同的结果。

最佳答案

我建议你探索 go 中的调度(来自 ardanlabs 的好文章)。

简短的回答是你无法控制执行顺序,go runtime 可以。同一个程序的每次执行都不会产生相同的执行轨迹。 Race detector跟踪每次运行的“活泼”行为,结果直接取决于调度程序的决定。

关于go - 如何修复 "one problem on race condition check which using go-build-race tools"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54249493/

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