Waiting for Our Goroutines to Finish
Understand how to use Go's sync.WaitGroup to manage and synchronize multiple goroutines. This lesson guides you through adding synchronization points to avoid race conditions and ensure your main function waits for all concurrent tasks to finish. You'll explore the Add Done and Wait methods and see practical examples to improve concurrency management in Go programs.
We'll cover the following...
It is not enough to create multiple goroutines—we also need to wait for them to finish before the main() function ends. Therefore, this lesson shows a technique that improves the code of multiple.go—the improved version is called varGoroutines.go. But first, we need to explain how this works.
The sync.WaitGroup variable
The synchronization process begins by defining a sync.WaitGroup variable and using the Add(), Done() and Wait() methods. If we look at the source code of the sync Go package, and more specifically at the waitgroup.go file, we see that the sync.WaitGroup type is ...