1 回答

TA貢獻(xiàn)1856條經(jīng)驗(yàn) 獲得超5個(gè)贊
因?yàn)橹?goroutine 在最后一個(gè)循環(huán)之后立即退出,導(dǎo)致整個(gè)程序也退出,所以后臺(tái) goroutines 可能會(huì)也可能不會(huì)有機(jī)會(huì)運(yùn)行,你必須提供一些同步方法來“等待”所有工作線程完成。for
用sync.WaitGroup
func main() {
concurrent := 12
ch := make(chan int)
var wg sync.WaitGroup
for i := 1; i <= concurrent; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
worker(i, ch)
}(i) // You have to pass i as parameter
}
for i := 1; i <= 21; i++ {
ch <- i
}
close(ch) // Close channel to tell all workers to stop
wg.Wait() // Wait all workers to finish its work
}
- 1 回答
- 0 關(guān)注
- 92 瀏覽
添加回答
舉報(bào)