Let golang close used channel after all goroutines finished

扶醉桌前 提交于 2019-11-30 15:17:44

The sync.WaitGroup type should encapsulate what you want to do, without needing sleep calls or busy waiting. It allows you to wait on an arbitrary number of tasks, not worrying about which order they complete.

Taking your original example, you could alter it to use a wait group like so:

var wg sync.WaitGroup
for i:=0; i<=10;i++{
    wg.Add(1)
    go func(){
        result:=calculate()
        c<-result
        wg.Done()
    }()
}
// Close the channel when all goroutines are finished
go func() {
    wg.Wait()
    close(c)
}()
for result:= range c{
    all_result=append(all_result, result...)
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!