Go by Example

WaitGroups

Use sync.WaitGroup to wait for a collection of goroutines to finish.

A goroutine is a function call started with go that can run while its caller continues. A sync.WaitGroup counts tasks so one goroutine can wait for them to finish. Call Add before starting each goroutine, Done when it finishes and Wait to pause until the count reaches zero.

When passing a wait group to another function, pass a pointer, a reference to the same wait group, so that function can update its count. Use defer to schedule Done for when the worker returns.

package main
 
import (
    "fmt"
    "sync"
)
 
func main() {
    var wg sync.WaitGroup
    for i := 1; i <= 3; i++ {
        wg.Add(1)
        go func(id int) {
            defer wg.Done()
            fmt.Println("worker", id)
        }(i)
    }
    wg.Wait()
    fmt.Println("all done")
}

In production

Do not copy a wait group after using it. Call Add before starting a goroutine, or Wait could finish before the task is counted. Done still runs if a function panics, meaning it stops because of an unexpected failure, but it does not stop that failure.

Enjoyed this? Get more software craft delivered to your inbox.