What is the Advantage of sync.WaitGroup over Channels?

后端 未结 6 723
旧巷少年郎
旧巷少年郎 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

    Independently of the correctness of your second example (as explained in the comments, you aren't doing what you think, but it's easily fixable), I tend to think that the first example is easier to grasp.

    Now, I wouldn't even say that channels are more idiomatic. Channels being a signature feature of the Go language shouldn't mean that it is idiomatic to use them whenever possible. What is idiomatic in Go is to use the simplest and easiest to understand solution: here, the WaitGroup convey both the meaning (your main function is Waiting for workers to be done) and the mechanic (the workers notify when they are Done).

    Unless you're in a very specific case, I don't recommend using the channel solution here.

提交回复
热议问题