gpt4 book ai didi

go - 带有sync.waitGroup的Goroutine每次输出不同的值

转载 作者:行者123 更新时间:2023-12-01 22:21:11 26 4
gpt4 key购买 nike

下面的代码每次执行后都会打印不同的值,但是我希望这些值相同,如何在不使用time.Sleep的情况下更改下面的代码

package main

import (
"fmt"
"sync"
)

var total int
var wg sync.WaitGroup

// Inc increments the counter for the given key.
func inc(num int) {
total += num
wg.Done()
}

// Value returns the current value of the counter for the given key.
func getValue() int {
return total
}

func main() {
for i := 1; i <= 1000; i++ {
wg.Add(1)
go inc(i)
}
wg.Wait()
fmt.Println(getValue())
}

最佳答案

您有一场数据竞赛,结果是不确定的。您必须同步对share变量的访问:

var total int
var lock sync.Mutex
var wg sync.WaitGroup

// Inc increments the counter for the given key.
func inc(num int) {
lock.Lock()
defer lock.Unlock()
total += num
wg.Done()
}

// Value returns the current value of the counter for the given key.
func getValue() int {
lock.Lock()
defer lock.Unlock()
return total
}
或者,使用 sync/atomic访问/修改变量。

关于go - 带有sync.waitGroup的Goroutine每次输出不同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63498025/

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