# Why would you use a Waitgroup

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 output[5](https://medium.com/@abhisheksah/golang-waitgroup-235531425dfd)[6](https://www.pixelstech.net/article/1682509796-Understand-GoLang-WaitGroup-internals-and-how-it-works).
    
* **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 zero[1](https://gist.github.com/humamfauzi/0b941dcb7ef4eacfd99695e29360721e)[5](https://medium.com/@abhisheksah/golang-waitgroup-235531425dfd)[6](https://www.pixelstech.net/article/1682509796-Understand-GoLang-WaitGroup-internals-and-how-it-works).
    
* **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.
