Wait for Goroutine to Finish With WaitGroup

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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
func myFunc() {
    println("myFunc is running")
    time.Sleep(5 * time.Second)
    println("myFunc is done")
}

func myOtherFunc() {
    println("myOtherFunc is running")
    time.Sleep(4 * time.Second)
    println("myOtherFunc is done")
}

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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import (
    "sync"
    "time"
)

func main() {
    var wg sync.WaitGroup

    wg.Add(1)
    go func() {
        myFunc()
        wg.Done()
    }()

    wg.Add(1)
    go func() {
        myOtherFunc()
        wg.Done()
    }()

    wg.Wait()
    
    println("continue the process...")
}

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.

go 

See also