gpt4 book ai didi

input - Go - 如何知道输出 channel 何时完成

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

我尝试按照 Rob Pike 在“并发不是并行”演讲中的例子做了如下事情:作为从输入 channel 读取数据、执行一些处理然后通过输出 channel 发送结果的工作人员,我正在启动许多 go 例程。

然后我启动另一个 go 例程,从某个来源读取数据并通过他们的输入 channel 将其发送给工作人员。最后,我想遍历输出 channel 中的所有结果并对它们进行处理。问题是因为工作在工作人员之间分配,我不知道所有工作人员何时完成,所以我可以停止向输出 channel 询问更多结果,我的程序可以正常结束。

了解工作人员何时将结果发送到输出 channel 的最佳做法是什么?

最佳答案

我个人喜欢为此使用 sync.WaitGroup。 WaitGroup 是一个同步计数器,它具有三种方法 - Wait()Done()Add()。您要做的是增加 WaitGroup 的计数器,将其传递给工作人员,并让他们在完成后调用 Done()。然后你只需阻塞另一端的 WaitGroup ,并在它们全部完成后关闭输出 channel ,导致输出处理器退出。

基本上:

// create the wait group
wg := sync.WaitGroup{}

// this is the output channel
outchan := make(chan whatever)

// start the workers
for i := 0; i < N; i++ {
wg.Add(1) //we increment by one the waitgroup's count

//the worker pushes data onto the output channel and calls wg.Done() when done
go work(&wg, outchan)
}

// this is our "waiter" - it blocks until all workers are done and closes the channel
go func() {
wg.Wait()
close(outchan)
}()

//this loop will exit automatically when outchan is closed
for item := range outchan {
workWithIt(item)
}

// TADA!

关于input - Go - 如何知道输出 channel 何时完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27594159/

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