What is the Advantage of sync.WaitGroup over Channels?

后端 未结 6 800
旧巷少年郎
旧巷少年郎 2021-01-30 10:33

I\'m working on a concurrent Go library, and I stumbled upon two distinct patterns of synchronization between goroutines whose results are similar:

Waitgroup



        
6条回答
  •  甜味超标
    2021-01-30 11:14

    It depends on the use case. If you are dispatching one-off jobs to be run in parallel without needing to know the results of each job, then you can use a WaitGroup. But if you need to collect the results from the goroutines then you should use a channel.

    Since a channel works both ways, I almost always use a channel.

    On another note, as pointed out in the comment your channel example isn't implemented correctly. You would need a separate channel to indicate there are no more jobs to do (one example is here). In your case, since you know the number of words in advance, you could just use one buffered channel and receive a fixed number of times to avoid declaring a close channel.

提交回复
热议问题