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.