Waiting for Our Goroutines to Finish

Let’s learn the basics of synchronizing goroutines.

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 nothing more than a structure with two fields:

Get hands-on with 1200+ tech skills courses.