Library contents

Go sync.WaitGroup

A WaitGroup tracks outstanding tasks. Add the task count before launching workers and call Done when each worker finishes.

A simple example

sync.WaitGroup

  1. Start with Two workers each finish once
  2. Do this Wait for both completions
  3. Result Wait returns after the second
The wait group tracks the remaining count. Each worker signals completion.

Syntax

Go syntax
group.Add(n) / group.Done() / group.Wait()
Run this example in Go

Save the program as main.go. Use Go 1.21 or later.

go run main.go

Wait for independent calculations before reading results

Independent jobs calculate separate parts of a report and can finish out of order. Combine their results only when every required calculation has completed so no contribution is missing.

From the programinputs := []int{2, 3, 4}
Result[4 9 16]
main.go
package main

import (
	"fmt"
	"sync"
)

func main() {
	inputs := []int{2, 3, 4}
	results := make([]int, len(inputs))
	var group sync.WaitGroup
	group.Add(len(inputs))
	for i := range inputs {
		go func(index int) {
			defer group.Done()
			results[index] = inputs[index] * inputs[index]
		}(i)
	}
	group.Wait()
	fmt.Println(results)
}
Output
[4 9 16]

Each goroutine writes a different slice element. Passing the index as an argument also works on Go versions with shared range variables. Reading after Wait produces deterministic output.

Go documentation for sync.WaitGroup

Advertisements

Combine two gallery entrances

Separate workers count admissions from the north and south doors. Wait until both workers have completed before summing their counts. What total can the coordinator publish?

GivenNorth 12 · South 8
Worked result20

Combine shift checkouts

Two desks count processed books independently before closing. Wait until both workers have completed before summing their counts. What total can the coordinator publish?

GivenDesk A 3 · Desk B 15
Worked result18