liveBook · Manning

WaitGroup.Wait

As explained in Go in Practice, Second Edition

The WaitGroup Wait method blocks until the wait group's tracked task count reaches zero.

WaitGroup.Wait blocks the calling goroutine until every task registered with the wait group has completed. Pair each launched goroutine with wg.Add(1) before starting it and wg.Done when it finishes; deferring Done reduces the chance of leaving Wait blocked. section 5.2.1

Figure 5.1 Start multiple workers and wait for completion.
figure

The worker timeline shows how multiple goroutines start and how Wait releases the caller only after completion. section 5.2.1

Parallel file compression

A parallel compressor calls wg.Add(1) for each filename, passes that filename into the goroutine, calls compress, then calls wg.Done. After the loop, wg.Wait ensures the completion message is printed only after all files finish. Passing the filename as a parameter prevents scheduled goroutines from observing a later loop value. section 5.2.1

How Go in Practice, Second Edition covers it

How deep it goes
Explains blocking behavior, Add and Done pairing, deferred cleanup, and loop-variable handling without descending into scheduler internals.
Examples
Uses a gzip compressor that processes command-line files in parallel and waits before reporting the count.
What it assumes
Assumes familiarity with goroutines and teaches the Add, Done, and Wait coordination pattern through a concrete program.
What you can do after
Operate a parallel Go workload that reports completion only after every registered goroutine finishes.
How it connects
Links goroutines with synchronization through sync.WaitGroup, deferred function calls, and closure argument passing.

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.