确定所有工人都完成

Determining all workers are done

下面Marcio's thread pool implementation是否可以确定所有工作何时完成?

等待 JobQueue 清空很简单:

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

但是之后可能还有goroutines在等待worker,或者worker还没有完成所有任务:

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()

根据文档。