gpt4 book ai didi

go - 确定所有 worker 都完成

转载 作者:数据小太阳 更新时间:2023-10-29 03:30:59 25 4
gpt4 key购买 nike

正在关注 Marcio's thread pool implementation是否可以确定所有工作何时完成?

等待 JobQueue 清空是微不足道的:

// Wait for the job queue to clear
for len(JobQueue) > 0 {
// Just wait
}

然而在那之后可能还有goroutines在等待workers,或者workers还没有完成所有的任务:

func (d *Dispatcher) dispatch() {
for {
select {
case job := <-JobQueue:
// a job request has been received
go func(job Job) {
// try to obtain a worker job channel that is available.
// this will block until a worker is idle
jobChannel := <-d.WorkerPool

// dispatch the job to the worker job channel
jobChannel <- job
}(job)
}
}
}

最好的方法是什么?在dispatcher中添加一个WaitGroup,以及查询WaitGroup状态的方法?对此的任何指示将不胜感激。

最佳答案

根据 the documentation :

A WaitGroup waits for a collection of goroutines to finish.

所以,是的,要等待一组 goroutine 完成,我会推荐一个 WaitGroup。正如文档所述,您为每个启动的工作人员调用 Add,并在每个工作人员完成时调用 Done。您的 for len() 繁忙循环将替换为:

wg.Wait()

根据文档。

关于go - 确定所有 worker 都完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51935169/

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