Concurrency

Go WaitGroup

Using WaitGroup

Go WaitGroup synchronizes goroutines with Add and Wait.

Introduction to Go WaitGroup

The WaitGroup in Go is a powerful concurrency primitive that allows developers to synchronize the execution of multiple goroutines. It is particularly useful for waiting for a collection of goroutines to finish their tasks before continuing the execution of the main program.

How WaitGroup Works

A WaitGroup has three primary methods: Add, Done, and Wait. These methods control and monitor the execution of goroutines:

  • Add(delta int): Increments the WaitGroup counter by the specified delta. Typically called before launching a goroutine.
  • Done(): Decrements the WaitGroup counter by one. This is usually called at the end of a goroutine.
  • Wait(): Blocks the calling goroutine until the WaitGroup counter is zero.

Using WaitGroup in a Simple Example

Explanation of the Example

In the above example:

  • A WaitGroup is declared and initialized in the main function.
  • The Add method is called before each goroutine is launched to increment the counter.
  • Each goroutine calls the Done method when it completes its task, decrementing the counter.
  • The Wait method blocks the main function until all the goroutines have finished executing, ensuring that "All workers completed" is printed only after all workers have finished.

Common Use Cases for WaitGroup

WaitGroup is commonly used when you need to:

  • Perform operations concurrently across multiple goroutines and wait for their completion.
  • Coordinate the startup and shutdown of a set of goroutines.
  • Aggregate results from multiple goroutines without locking the main thread.

Best Practices When Using WaitGroup

  • Avoid copying a WaitGroup after the first use as it might lead to unexpected behavior.
  • Always ensure that Done is called to prevent the Wait method from blocking indefinitely.
  • Use Add before launching the goroutine to avoid race conditions.
Previous
Mutex