Skip to main content

Command Palette

Search for a command to run...

Why would you use a Waitgroup

Published
•2 min read•View as Markdown

A WaitGroup is used in Go to coordinate and synchronize the completion of multiple concurrent operations, typically goroutines. Its primary purpose is to ensure that a program waits for a collection of goroutines to finish before proceeding, preventing premature exit or continuation of the main routine while background tasks are still running

Why Use a WaitGroup?

  • Synchronization of Goroutines: When you launch several goroutines, the main function (or any parent goroutine) does not automatically wait for them to finish. Without synchronization, the main function might exit before the goroutines complete, causing unfinished work or missing output56.

  • Thread-safe Counter: WaitGroup acts as a thread-safe counter. You increment the counter with Add(n) for the number of goroutines you want to wait for, decrement it with Done() when each goroutine finishes, and block execution with Wait() until the counter reaches zero156.

  • Simple and Efficient: WaitGroup provides a simple API with just three methods—Add(), Done(), and Wait()—making it easy to use for most concurrency synchronization needs

Typical Usage Scenario

Suppose you want to run several tasks concurrently and only proceed when all of them are done (for example, fetching data from multiple sources in parallel). You would:

  1. Create a WaitGroup.

  2. Call Add(n) where n is the number of goroutines to wait for.

  3. Launch each goroutine, making sure each calls Done() when finished.

  4. Call Wait() in the main goroutine to block until all tasks are complete.