1 回答

TA貢獻2037條經驗 獲得超6個贊
你可以使用一個sync.WaitGroup
例如
package main
import "sync"
func main() {
// Some sort of job queue for your workers to process. This job queue should be closed by the process
// that populates it with items. Once the job channel is closed, any for loops ranging over the channel
// will read items until there are no more items, and then break.
jobChan := make(chan JobInfo)
// Populate the job queue here...
// ...
close(jobChan)
// We now have a full queue of jobs that can't accept new jobs because the channel is closed.
// Number of concurrent workers.
workerCount := 10
// Initialize the WaitGroup.
wg := sync.WaitGroup{}
wg.Add(workerCount)
// Create the worker goroutines.
for i := 0; i < workerCount; i++ {
go func() {
// When the jobChan is closed, and no more jobs are available on the queue, the for loop
// will exit, causing wg.Done() to be called, and the anonymous function to exit.
for job := range jobChan {
// Process job.
}
wg.Done()
}()
}
// Wait for all workers to call wg.Done()
wg.Wait()
// Whatever you want to do after all queue items have been processed goes here.
// ...
}
- 1 回答
- 0 關注
- 202 瀏覽
添加回答
舉報