WaitGroup
In the previous exercise, we used a not-so-elegant method to ensure that the Goroutine ended by making the main Goroutine wait for a second. The important thing to understand is that even if a program does not explicitly use Goroutines via the go
call, it still uses one Goroutine, which is the main routine. When we run our program and create a new Goroutine, we are running two Goroutines: the main one and the one we just created. In order to synchronize these two Goroutines, Go gives us a function called WaitGroup
. You can define a WaitGroup
using the following code:
wg := sync.WaitGroup{}
WaitGroup
needs the sync
package to be imported. Typical code using the WaitGroup
will be something like this:
package main import "sync" func main() { wg := &sync.WaitGroup{} wg.Add(1) ………………….. wg.Wait() …………. …...