liveBook · Manning

WaitGroup

As explained in Go in Practice, Second Edition

A wait group is a synchronization primitive that lets a program wait for a collection of concurrent tasks to finish.

A WaitGroup coordinates concurrent work when one goroutine must start several others and wait until every task finishes. It is useful when independent jobs, such as file compression, should run in parallel before a summary is displayed. section 5.2.1

Use the synchronization count around each worker:

Listing 5.3 Compressing files in parallel with a wait group
package main

import (
     "compress/gzip"
     "fmt"
     "io"
     "os"
     "sync"
)

func main() {
     var wg sync.WaitGroup                #1
     for i, file := range os.Args[1:] {
            wg.Add(1)                        #2
            go func(filename string) {     #3
                   compress(filename)      #3
                   wg.Done()               #3
            }(file)                              #4
     }
     wg.Wait()                                               #5
     fmt.Printf("Compressed %d files\n", len(os.Args[1:]))
}

func compress(filename string) error {
     // Unchanged from above
}

A complete parallel file-compression example applies Add, launches workers, signals Done, waits for completion, and prints the compressed-file count. section 5.2.1

How Go in Practice, Second Edition covers it

How deep it goes
Defines count-based synchronization and demonstrates Add, Done, and Wait in a parallel file-compression program.
Examples
Uses command-line file compression with compress/gzip and produces .gz files before printing a summary.
What it assumes
Assumes goroutines and concurrent task execution while using Go standard-library synchronization.
What you can do after
Build it from scratch by coordinating multiple goroutines and waiting for their completion.
How it connects
Connects goroutines, worker delegation, synchronization, and file compression.

Also explained in

Compare how 5 books explain WaitGroup →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Go in Practice, Second Edition. The section links point to the parts of the book it draws on.