In this article, we explore how to use WaitGroups to enhance concurrent programs in Go. Specifically, we will modify a program that calculates the squares of numbers using Goroutines by adding synchronization through the sync package’s WaitGroup. This ensures that the main function waits for all Goroutines to complete before exiting. Previously, the following program calculated squares concurrently without synchronization:Documentation Index
Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
Use this file to discover all available pages before exploring further.
Adding a WaitGroup
To synchronize the Goroutines, we introduce a WaitGroup from the sync package. First, declare a WaitGroup variable and set its counter to 10 (the number of Goroutines):The code above sets the WaitGroup counter to 10 with
wg.Add(10), but currently, it does not indicate when individual Goroutines complete their work.Signaling Completion with Done()
To update the WaitGroup counter as each Goroutine completes its execution, modify thecalculateSquare function to accept a pointer to the WaitGroup and call the Done() method right after processing the square calculation. This can be implemented using defer wg.Done():
wg.Done() after computing the square, which decrements the WaitGroup counter. The wg.Wait() in the main function ensures that the program only proceeds once all Goroutines have finished executing.
Execution and Output
To run the program, execute the following command in your terminal:In the next lesson, we will delve into more advanced topics with Goroutines and concurrency in Go.