Let golang close used channel after all goroutines finished

后端 未结 1 1221
孤街浪徒
孤街浪徒 2021-01-03 01:36

I am trying to run a number of goroutines which will give their results to a channel. I need a good way to let channel close after all goroutines are done.

My first

相关标签:
1条回答
  • 2021-01-03 02:10

    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...)
    }
    
    0 讨论(0)
提交回复
热议问题