gpt4 book ai didi

go - 如何在golang中解决种族状况?

转载 作者:行者123 更新时间:2023-12-01 22:45:55 27 4
gpt4 key购买 nike

我正在尝试修复golang中的比赛条件,我使用了waitgroup,因为您可以看到我添加了两个waitgroup并调用Done()。但是仍然无法保护输出。

package main

import (
"fmt"
"time"
"sync"
)

var counter int = 0

func task(m string, n int, wg *sync.WaitGroup) {
defer wg.Done()
for i := 0 ; i < 100 ; i++ {
counter = n
time.Sleep(100000)
fmt.Println(m, counter)
counter = 0
}
}

func main() {
var wg sync.WaitGroup
wg.Add(1)
go task("first", 1, &wg) // i want "first" task should get always 1
wg.Add(1)
go task("second", 2, &wg) // // i want "second" task should get always 2
wg.Wait()
}
以上程序输出
second 1
first 1
first 1
second 1
first 2
second 2
second 2
...
预期产量
second 2
first 1
first 1
second 2
first 1
second 2
second 2
...

最佳答案

任何正在寻找如何使用sync.Mutex进行golang同步的用户。这可能会有所帮助。如果此解决方案不正确,请发表评论或回复。

package main

import (
"fmt"
"time"
"sync"
)

var counter int = 0

func task(m string, n int, wg *sync.WaitGroup, mux *sync.Mutex) {

defer wg.Done()
for i := 0 ; i < 100 ; i++ {
mux.Lock()
//your shared resource
counter = n
time.Sleep(100000)
fmt.Println(m, counter)
counter = 0
//end of your shared resource
mux.Unlock()
}
}

func main() {
var wg sync.WaitGroup
var mux sync.Mutex
wg.Add(1)
go task("first", 1, &wg, &mux)
wg.Add(1)
go task("second", 2, &wg, &mux)
wg.Wait()
}

关于go - 如何在golang中解决种族状况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63398363/

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