Using WaitGroup in Goroutines

GoGoBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

The waitgroups challenge is designed to help you understand how to use a wait group to wait for multiple goroutines to finish.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL go(("`Go`")) -.-> go/ConcurrencyGroup(["`Concurrency`"]) go/ConcurrencyGroup -.-> go/waitgroups("`Waitgroups`") subgraph Lab Skills go/waitgroups -.-> lab-15449{{"`Using WaitGroup in Goroutines`"}} end

waitgroups

The problem to be solved in this challenge is to launch several goroutines and increment the WaitGroup counter for each. Then, we need to wait for all the goroutines launched to finish.

Requirements

  • Basic knowledge of Golang.
  • Understanding of concurrency in Golang.
  • Familiarity with the sync package.

Example

$ go run waitgroups.go
Worker 5 starting
Worker 3 starting
Worker 4 starting
Worker 1 starting
Worker 2 starting
Worker 4 done
Worker 1 done
Worker 2 done
Worker 5 done
Worker 3 done

## The order of workers starting up and finishing
## is likely to be different for each invocation.

Summary

In this challenge, we learned how to use a wait group to wait for multiple goroutines to finish. We also learned how to launch several goroutines and increment the WaitGroup counter for each. Finally, we saw how to wait for all the goroutines launched to finish.

Other Go Tutorials you may like