Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is sync.WaitGroup an implementation of Barrier?

Tags:

go

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 ?

like image 425
canadadry Avatar asked Mar 27 '14 18:03

canadadry


1 Answers

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.

like image 147
Stephen Weinberg Avatar answered Oct 12 '22 14:10

Stephen Weinberg