gpt4 book ai didi

go - 如何让多个 goroutine 等待另一个 goroutine 的输出

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

Main {
go routine_1(carryout a time consuming task and return output)
go routine_2(wait for output from routine_1, collect output and do task_2)
go routine_3(wait for output from routine_1, collect output and do task_3)
wait for all routines to complete
}

我使用过 channel ,但是一旦routine_2 读取数据routine_3 就没有得到数据。

我不希望主线程进行同步,即知道routine_2、routine_3 到routine_1 之间的依赖关系

事实证明,关闭 channel 将为其他例程提供所需的广播,以了解结果已准备好。

谢谢你的时间。(这是我在stackoverflow的第一个问题,很高兴看到这么好的质量和快速的回​​复)谢谢大家。

更新我选择的答案。再次感谢。
package main

import (
"fmt"
"sync"
)

func computeResult() int {
return 100
}

func main() {

var wg sync.WaitGroup
wg.Add(2)
var output int

ch := make(chan struct{})

// Compute result
go func() {
defer wg.Done()
output = computeResult()
fmt.Println("closing channel to signal task done")
close(ch)
fmt.Println("channel closed")

}()

go func() {
defer wg.Done()
// Wait for ch close
<-ch
fmt.Println(output)
}()

wg.Wait()

var wg2 sync.WaitGroup
wg2.Add(1)

go func() {
defer wg2.Done()
fmt.Println("wait on closed channel")
// Wait for ch close
<-ch
fmt.Println(output)
}()

wg2.Wait()

}

最佳答案

您可以在第一个例程完成后调用其他两个例程:

var wg sync.WaitGroup
wg.Add(2)
go func() {
output := task1()
go func() {
defer wg.done()
task2(output)
}
go func() {
defer wg.done()
task3(output)
}
}()
wg.Wait()

关于go - 如何让多个 goroutine 等待另一个 goroutine 的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58346641/

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