Level Up Coding

Coding tutorials and news. The developer homepage gitconnected.com && skilled.dev && levelup.dev

Follow publication

Member-only story

Use the WaitGroup Wisely in Concurrent Programs in Go

Jerry An
Level Up Coding
Published in
2 min readMay 1, 2022

Photo by Marco López on Unsplash

WaitGroup is a synchronization primitive that lets your program know when a set of goroutines have been completed.

In this post, we will explore when and how to use it to synchronize the execution of goroutines.

Start From An Example

The following is a simple example of WaitGroup usage.

  • Line # 1: create a WaitGroup variable
  • Line #3–#10: define two different functions to run in separate goroutines.
  • Line #12: add two goroutines to the WaitGroup.
  • Line #14–#15: start the two goroutines.
  • Line #17 the main goroutine waits for the two goroutines to finish
  • The End
A sequence of WaitGroup example

As shown in the example, the WaitGroup is like that can be incremented and decremented. We call the Add

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

No responses yet

Write a response