Goroutine is very useful to execute a process asynchronously. You can use multiple goroutines to run multiple processes at the same time. But what if you want to wait for the goroutines to finish before continue to the next process? You can use WaitGroup to wait for goroutines to finish.
What is WaitGroup
WaitGroup is a built-in Go struct from the sync
package. It waits for multiple goroutines to finish. Let’s explore how to use WaitGroup in Go.
How to use WaitGroup
Say that we have these two functions:
|
|
We want to execute these 2 functions at the same time and wait for them to finish before continuing the process. We will use WaitGroup to do that. See the example below about how to use the WaitGroup.
|
|
First, we declare the WaitGroup variable on line 7. For each goroutine, we need to call wg.Add(1)
before executing the process in the goroutine, and wg.Done()
after it finishes. Don’t forget to call wg.Done()
or your program will wait indefinitely. Then we use wg.Wait()
to wait for all processes to finish. The process will continue if all processes are executed.
Conclusion
There are many ways to wait for goroutines to finish. One of the ways is by using WaitGroup. This is a simple basic usage of WaitGroups. If you have any suggestions or questions, please leave a comment in the comment section below.