Waitgroups
This page is under active revision, content may be updated without notice
In previous chapters, we talked about how goroutines in Go language works. We have also seen several hacks to make our main
program wait for goroutines. We have seen another strategy to make our main
program wait in Channel Synchronization chapter. we have gone through Select chapter. Today we will focus on providing robustness to our previous chapters by using semaphores from sync package, specially sync.WaitGroup
In Go, sync.WaitGroup implements three methods, Add
, Done
and Wait
. We will discuss them at length. But before we jump for an example, in brief, goroutine with wait will wait for other goroutines (number of which are incremented by Add) to finish and call Done on WaitGroup before exiting.
Here is redone example from our previous chapter
Results may vary from machines to machines and specific to implementation. The message is that how one can leverage sync.WaitGroup
api to synchronize goroutines. Believe me, illustration above is very basic example of what can be achieved with WaithGroup. But in essence what we did is, we imported sync
package. sync
package contains WaitGroup
type, we declared variable wait
to be of WaitGroup type. Waitgroup
provides three methods namely Add
, Done
and Wait
.
1.) Add
method takes integer as a parameter delta to the counter, and once counter becomes zero, all blocking goroutines, waiting onto counter would be released. We provided no of goroutines we are going to wait upon
Note, that in illustration above, we provided our goroutine count at once to be 10. But in practical scenario, calling wait.Add(1)
will increment counter by one.
2.) Wait
methods waits for semaphore counter to become zero, before releasing goroutines, waiting onto other goroutines to terminate/finish. In illustration above, we are making our main program to wait for other goroutines to finish.
3.) Done
method basically indicates that current goroutine, in which this is being called is done/finished, while decrementing semaphore counter. Our goroutines calls to Done
method indicating that goroutine is done executing its task.
Last updated