liveBook · Manning

Sync package

As explained in Learn Go with Pocket-Sized Projects

sync is Go's standard-library package providing synchronization primitives such as mutexes, wait groups, and once-only execution controls.

The sync package provides synchronization tools for coordinating goroutines. Its WaitGroup type replaces a channel-based waiting pattern when a program must wait for several goroutines to finish. section 7.2.4

Use a WaitGroup by following this sequence:

  • Create a WaitGroup, commonly as wg := &sync.WaitGroup{}. section 7.2.4
  • Call Add with the number of goroutines to track before launching them. section 7.2.4
  • Pass the pointer to each goroutine and defer Done so the shared WaitGroup is notified even when the function returns. section 7.2.4
  • Call Wait after launching the goroutines; it returns after the matching Done calls. section 7.2.4
Listing 7.7 Cooking example using sync.WaitGroup
package main

import (
    "fmt"
    "sync"
)

func main() {
    wg := &sync.WaitGroup{} #1
    wg.Add(2) #2

    go cookRice(wg) #3
    go cookCurry(wg)  #3

    wg.Wait() #4
}

func cookRice(wg *sync.WaitGroup) {
    defer wg.Done() #5
    fmt.Println("Cooking rice...")
    // prepare rice
}

func cookCurry(wg *sync.WaitGroup) {
    defer wg.Done() #5
    fmt.Println("Preparing curry sauce...")
    // prepare curry
}

A complete cooking example coordinates rice and curry goroutines with Add, deferred Done, and Wait. section 7.2.4

How Learn Go with Pocket-Sized Projects covers it

How deep it goes
Explains WaitGroup construction, Add, Done, Wait, deferred cleanup, and pointer semantics, but does not detail other sync types.
Examples
Demonstrates cooking rice and curry concurrently, including an error-channel variant and an errgroup.Group variant.
What it assumes
Assumes familiarity with goroutines and channels while teaching WaitGroup coordination from its construction through completion.
What you can do after
Apply it via Go's sync.WaitGroup to wait reliably for launched goroutines to complete.
How it connects
Connects WaitGroup to goroutines, channels, and errgroup.Group as alternative coordination mechanisms.

Also explained in

Compare how 3 books explain sync package →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Go with Pocket-Sized Projects. The section links point to the parts of the book it draws on.