A Barrier in the synchronization world allows threads to wait for other threads to reach a certain point. A counting semaphore allows n numbers of threads to access a shared resource.
So from this, a sync.WaitGroup
is a cross between a Barrier & a counting Semaphore (but without any concept of shared resource). Is this an accurate mental model ?
Many things can be used as barriers. In go, the most idiomatic barrier is a channel. If you have more than one goroutine you are waiting for, then a waitgroup can be useful.
While a waitgroup can be used as a barrier dealing with threads (goroutines), that isn't all it can do. You could have N jobs sent to M goroutines and then have the waitgroup track jobs instead of goroutines that are finished.
The purpose of a waitgroup is simply to wait for the number of events you were expecting to occur. This could be because goroutines got to a certain place in the code, jobs were completed, or you just felt like it. If you have a mental model of it as just a barrier, it will limit your uses of it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With