
Declaring and Using a WaitGroup
To get started, declare a WaitGroup just like any other variable using thevar keyword. For example:
sync package at the beginning of your file:
-
Add
Use this method to set the number of goroutines that the WaitGroup should wait for. It increases the internal counter by the specified number. -
Wait
This method blocks the execution of the code until the WaitGroup’s internal counter reaches zero. Typically, you call it after all desired goroutines have been launched. -
Done
Each goroutine should callwg.Done()when its work is completed. This method decreases the WaitGroup’s counter by one.
Ensure that every call to
wg.Add(n) eventually corresponds to n calls to wg.Done(). Failing to do so will result in your program hanging indefinitely.Understanding WaitGroups with an Example
Consider a scenario where you need to manage three concurrent tasks. Initially, the WaitGroup’s counter is zero. By invokingwg.Add(3), the counter is increased to three. Each of the three goroutines will call wg.Done() upon task completion, decrementing the counter by one. Meanwhile, wg.Wait() blocks further execution until all goroutines complete and the counter reaches zero.
Below is a consolidated example that demonstrates the use of WaitGroups:
- The main function sets the WaitGroup counter to 3 using
wg.Add(3). - Three goroutines are spawned, each executing the
workerfunction. - Each worker calls
wg.Done()after finishing its task. - The main goroutine waits on
wg.Wait(), ensuring that it only proceeds after every worker has completed execution.
Using WaitGroups correctly helps to avoid potential issues with premature termination of your main routine, maintaining the reliability and predictability of concurrent execution.