Synchronizing goroutines with WaitGroup
While working with concurrently running code branches, it is no exception that at some point the program needs to wait for concurrently running parts of the code. This recipe gives insight into how to use the WaitGroup
to wait for running goroutines.
How to do it...
- Open the console and create the folder
chapter10/recipe05
. - Navigate to the directory.
- Create the file
syncgroup.go
with the following content:
package main import "sync" import "fmt" func main() { wg := &sync.WaitGroup{} for i := 0; i < 10; i++ { wg.Add(1) go func(idx int) { // Do some work defer wg.Done() fmt.Printf("Exiting %d\n", idx) }(i) } wg.Wait() fmt.Println("All done.") }
- Execute the code by
go run syncgroup.go
. - See the output:

How it works...
With help of the WaitGroup
struct from the sync
package, the program...