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
WaitGroupis declared and initialized in themainfunction. - The
Addmethod is called before each goroutine is launched to increment the counter. - Each goroutine calls the
Donemethod when it completes its task, decrementing the counter. - The
Waitmethod 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
WaitGroupafter the first use as it might lead to unexpected behavior. - Always ensure that
Doneis called to prevent theWaitmethod from blocking indefinitely. - Use
Addbefore launching the goroutine to avoid race conditions.
Concurrency
- Channels
- Goroutines
- Select
- Mutex
- WaitGroup
- Atomic Operations
- Previous
- Mutex
- Next
- Atomic Operations