1 回答

TA貢獻(xiàn)1785條經(jīng)驗 獲得超4個贊
關(guān)閉jobsCh導(dǎo)致工人退出:
func addJobs(jobsCh chan<- int, wg *sync.WaitGroup) {
// 100 numbers to crunch (jobs)
for i := 1; i < 101; i++ {
jobsCh <- i
}
close(jobsCh) // <-- add this line
wg.Done()
}
工作人員完成后,關(guān)閉resultsCh導(dǎo)致結(jié)果循環(huán)退出:
func addWorkers(jobsCh <-chan int, resultsCh chan<- int, wg *sync.WaitGroup) {
var wg2 sync.WaitGroup
// 10 workers
for i := 0; i < 10; i++ {
wg2.Add(1)
go worker(jobsCh, resultsCh, &wg2)
}
wg2.Wait() // <-- add this line
close(resultsCh) // and this line
wg.Done()
}
- 1 回答
- 0 關(guān)注
- 86 瀏覽
添加回答
舉報