SyntaxPilot
Courses/Go Programming/Lesson 45
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

Go Programming · Lesson 45 of 89

WaitGroup and Mutex

sync.WaitGroupAddDoneWaitWaitGroup.Go (Go 1.25)race conditioncritical sectionsync.MutexLock and Unlockdefer Unlocksync.RWMutexRLocklock granularitymutex embedded in structs

These are the notes for Go episode 45. Raju's cloud kitchen sends five delivery boys (goroutines) out at closing time. He wants to pull the shutter down only when all of them are back. You invent the tool for that: first main doesn't wait at all and nothing is delivered, then sleeping a guess loses orders, then a counter board, which is Go's sync.WaitGroup. Then a second problem: a thousand cooks add to one shared tally, and hundreds of thousands of rotis vanish. That's a race condition, and you fix it with a critical section guarded by sync.Mutex. Along the way: defer mu.Unlock(), sync.RWMutex for many readers, lock granularity, a mutex inside a struct, and the copied-lock bug that go vet catches.

All outputs and errors here are from real runs (Go 1.25.1, linux/amd64, a machine with 2 CPUs). Timings and the numbers from racy programs change on every run; the shape stays the same.

Facts and sources

  • Go 1.25 release notes: "The latest Go release, version 1.25, arrives in August 2025, six months after Go 1.24." In the sync package: "The new WaitGroup.Go method makes the common pattern of creating and counting goroutines more convenient." In go vet: a new "waitgroup" analyzer "reports misplaced calls to sync.WaitGroup.Add".
  • Data Race Detector (Go docs): "A data race occurs when two goroutines access the same variable concurrently and at least one of the accesses is a write." (The detector itself is episode 46.)
  • The Go Memory Model: "For any sync.Mutex or sync.RWMutex variable l and n < m, call n of l.Unlock() is synchronized before call m of l.Lock() returns." In plain words: whatever a goroutine wrote before Unlock is visible to the next goroutine after its Lock.
  • WaitGroup.Go needs Go 1.25 or newer; with an older go line in go.mod, go vet reports sync.Go requires go1.25 or later (module is go1.24). On older versions use wg.Add(1) + go + defer wg.Done().

The problem: closing too early

In Raju's kitchen In Go
5 delivery boys ride at the same time 5 goroutines started with go (episode 43)
Raju pulls the shutter down right away main returns
the boys' work is thrown away when main returns, the whole program ends, even with goroutines still running
package main

import (
    "fmt"
    "time"
)

// a delivery boy takes an order to a customer
func deliver(order int) {
    time.Sleep(100 * time.Millisecond) // the ride
    fmt.Println("order", order, "delivered")
}

func main() {
    for order := 1; order <= 5; order++ {
        go deliver(order)
    }
    fmt.Println("shop closed")
}

Real output:

shop closed

Not a single order is delivered: main printed its line and returned long before any 100 ms ride finished.

Attempt 2: sleep and hope

package main

import (
    "fmt"
    "time"
)

// order 1 is near, order 5 is far: rides take 100 to 500 ms
func deliver(order int) {
    time.Sleep(time.Duration(order) * 100 * time.Millisecond)
    fmt.Println("order", order, "delivered")
}

func main() {
    for order := 1; order <= 5; order++ {
        go deliver(order)
    }
    time.Sleep(250 * time.Millisecond) // guess: is 250 ms enough?
    fmt.Println("shop closed")
}

Real output:

order 1 delivered
order 2 delivered
shop closed

Orders 3, 4 and 5 are lost. A longer guess wastes time on every run, and on a slow, busy machine any guess can be wrong. Why it fails: main has no way to know when the goroutines are finished. It needs a count of how many are still running, not a timer.

The fix: sync.WaitGroup

Synchronisation means making goroutines coordinate: one waits for another, or they take turns. The sync package holds Go's basic synchronisation tools.

A sync.WaitGroup is a counter board at the door:

Counter board WaitGroup When
a boy leaves: +1 wg.Add(1) before the go statement
a boy returns: −1 wg.Done() (same as wg.Add(-1)) at the end of the goroutine, usually defer wg.Done()
Raju waits until the board shows 0 wg.Wait() blocks until the counter is 0

The zero value of a WaitGroup is ready to use (counter 0): var wg sync.WaitGroup. Blocks means the goroutine stops at that line and sleeps (using no CPU) until the condition is met.

package main

import (
    "fmt"
    "sync"
    "time"
)

func deliver(order int, wg *sync.WaitGroup) {
    defer wg.Done() // tick: one more boy is back
    time.Sleep(time.Duration(order) * 100 * time.Millisecond)
    fmt.Println("order", order, "delivered")
}

func main() {
    start := time.Now()
    var wg sync.WaitGroup // the counter starts at 0
    for order := 1; order <= 5; order++ {
        wg.Add(1) // one more boy is out
        go deliver(order, &wg)
    }
    wg.Wait() // wait until the counter is back to 0
    took := time.Since(start).Round(100 * time.Millisecond)
    fmt.Println("shop closed after", took)
}

Real output:

order 1 delivered
order 2 delivered
order 3 delivered
order 4 delivered
order 5 delivered
shop closed after 500ms

Exactly the slowest ride: main waits as long as needed and no longer.

Notes: - Pass the WaitGroup as a pointer (&wg, type *sync.WaitGroup): every goroutine must change the same board. A copy would be a different board (see the copied-lock bug below; a WaitGroup must not be copied either). - defer wg.Done() (defer from episode 10) runs on every way out of the function, including a panic. - Done happening is synchronized before Wait returning, so everything a goroutine wrote before Done is visible after Wait (more in episode 46).

WaitGroup mistakes

1. Forgetting Done → deadlock

package main

import (
    "fmt"
    "sync"
)

func main() {
    var wg sync.WaitGroup
    for order := 1; order <= 3; order++ {
        wg.Add(1)
        go func() {
            fmt.Println("order", order, "delivered")
            // oops: no wg.Done()
        }()
    }
    wg.Wait()
    fmt.Println("shop closed")
}

Real output (the three lines come in a different order on each run):

order 3 delivered
order 1 delivered
order 2 delivered
fatal error: all goroutines are asleep - deadlock!

goroutine 1 [sync.WaitGroup.Wait]:
sync.runtime_SemacquireWaitGroup(0xc000010110?, 0x80?)
    /usr/local/go1.25.1/src/runtime/sema.go:114 +0x2e
sync.(*WaitGroup).Wait(0xc0000100e0)
    /usr/local/go1.25.1/src/sync/waitgroup.go:206 +0x85
main.main()
    main.go:17 +0x8b
exit status 2

A deadlock is when goroutines wait for something that can never happen. Here the counter is stuck at 3 and no goroutine is left to lower it. The runtime noticed that every goroutine was blocked and stopped the program. (If some other goroutine were still running, for example a web server, the runtime could not tell, and the program would just hang.)

2. Done more often than Add → negative counter

package main

import "sync"

func main() {
    var wg sync.WaitGroup
    wg.Add(1)  // one boy goes out
    wg.Done()  // he comes back
    wg.Done()  // ...and is counted back again
}

Real output:

panic: sync: negative WaitGroup counter

goroutine 1 [running]:
sync.(*WaitGroup).Add(0xc000106000, 0xffffffffffffffff)
    /usr/local/go1.25.1/src/sync/waitgroup.go:118 +0x23a
sync.(*WaitGroup).Done(...)
    /usr/local/go1.25.1/src/sync/waitgroup.go:156
main.main()
    main.go:9 +0x4d
exit status 2

Every Add(1) needs exactly one Done().

3. Add inside the goroutine → Wait returns too early

// files: go.mod (module shop, go 1.25) and main.go
package main

import (
    "fmt"
    "runtime"
    "sync"
    "time"
)

func main() {
    runtime.GOMAXPROCS(1) // one P: the timing bug shows every time
    var wg sync.WaitGroup
    for order := 1; order <= 5; order++ {
        go func() {
            wg.Add(1) // counted too late: inside the goroutine
            defer wg.Done()
            time.Sleep(100 * time.Millisecond)
            fmt.Println("order", order, "delivered")
        }()
    }
    wg.Wait()
    fmt.Println("shop closed")
}

Real output of go run . then go vet .:

$ go run .
shop closed
$ go vet .
# shop
# [shop]
./main.go:15:19: WaitGroup.Add called from inside new goroutine

runtime.GOMAXPROCS(1) (episode 44) leaves one P, so the new goroutines can't run until main blocks. main reached Wait before any goroutine had run its Add, so the counter was still 0 and Wait returned at once. With more Ps it depends on timing (in one of our runs without GOMAXPROCS(1) all five orders were delivered), which makes it worse: it may work on your laptop and fail on a server. The vet check looks for Add as the first statement of the goroutine's function literal. Go 1.25's go vet (the static checker from episode 2) reports it with the new waitgroup analyzer.

WaitGroup.Go (Go 1.25)

wg.Go(f) does Add(1), starts f in a new goroutine, and calls Done when f returns. You can't forget any part or put Add in the wrong place.

package main

import (
    "fmt"
    "sync"
    "time"
)

func main() {
    start := time.Now()
    var wg sync.WaitGroup
    for order := 1; order <= 5; order++ {
        wg.Go(func() { // Go 1.25: Add(1), go and Done in one call
            time.Sleep(time.Duration(order) * 100 * time.Millisecond)
            fmt.Println("order", order, "delivered")
        })
    }
    wg.Wait()
    took := time.Since(start).Round(100 * time.Millisecond)
    fmt.Println("shop closed after", took)
}

Real output: the same five lines and shop closed after 500ms.

The function literal uses order directly: since Go 1.22 every loop iteration has its own order variable (episode 8), so each goroutine sees its own value.

wg.Go takes a func() with no arguments and no results. To pass something in, capture it in a closure (episode 10), as above.

The next problem: a shared tally (race conditions)

package main

import (
    "fmt"
    "sync"
)

func main() {
    rotis := 0 // the shared tally on the wall
    var wg sync.WaitGroup
    for cook := 1; cook <= 1000; cook++ {
        wg.Go(func() {
            for i := 0; i < 1000; i++ {
                rotis++ // each cook adds 1000 rotis
            }
        })
    }
    wg.Wait()
    fmt.Println("expected 1000000, tally says", rotis)
}

Real output, three runs on our 2-CPU machine while it was otherwise idle:

expected 1000000, tally says 695792
expected 1000000, tally says 901312
expected 1000000, tally says 923665

No error, no crash, just wrong data, different every time. And sometimes it prints exactly 1000000: when the machine was busy with other work, five runs in a row were correct, because each goroutine happened to finish before another one ran. A test that passes is no proof there is no race (episode 46 shows the tool that proves it).

In the video we write the three steps out and let another goroutine run between the read and the write, with runtime.Gosched() (episode 43), so the bug shows on every run:

package main

import (
    "fmt"
    "runtime"
    "sync"
)

func main() {
    rotis := 0 // the shared tally on the wall
    var wg sync.WaitGroup
    for cook := 1; cook <= 1000; cook++ {
        wg.Go(func() {
            for i := 0; i < 1000; i++ { // rotis++, step by step:
                n := rotis        // read the tally
                runtime.Gosched() // another cook gets a turn here
                rotis = n + 1     // add one, write it back
            }
        })
    }
    wg.Wait()
    fmt.Println("expected 1000000, tally says", rotis)
}

Real output, two runs:

expected 1000000, tally says 1684
expected 1000000, tally says 4018
  • A race condition is a bug where the result depends on the timing of goroutines (who happens to get there first).
  • Here it comes from a data race: two goroutines access the same variable at the same time, at least one of them writes, and nothing orders the accesses.
  • rotis++ looks like one step but is three: read the value, add 1, write it back.
Step Cook A Cook B tally
1 reads 41 41
2 reads 41 41
3 writes 42 42
4 writes 42 42

Two rotis, but the tally went up by one: a lost update.

Critical sections and sync.Mutex

  • A critical section is the part of the code that reads or writes shared data. The rule: only one goroutine inside it at a time.
  • Keeping everyone else out while one goroutine is inside is mutual exclusion, and the tool is a mutex (from mutual exclusion): one piece of chalk; only the cook holding it may touch the tally.
  • var mu sync.Mutex creates one; its zero value is an unlocked mutex.
  • mu.Lock() takes it. If another goroutine holds it, Lock blocks until it is free.
  • mu.Unlock() gives it back.
package main

import (
    "fmt"
    "sync"
)

func main() {
    rotis := 0
    var mu sync.Mutex // the one piece of chalk
    var wg sync.WaitGroup
    for cook := 1; cook <= 1000; cook++ {
        wg.Go(func() {
            for i := 0; i < 1000; i++ {
                mu.Lock()   // take the chalk, or wait for it
                rotis++     // critical section: one cook at a time
                mu.Unlock() // put the chalk back
            }
        })
    }
    wg.Wait()
    fmt.Println("expected 1000000, tally says", rotis)
}

Real output (every run):

expected 1000000, tally says 1000000

The step-by-step version from the video, with the same lock:

            for i := 0; i < 1000; i++ { // rotis++, step by step:
                mu.Lock()         // take the chalk, or wait for it
                n := rotis        // critical section starts
                runtime.Gosched() // others may run, but not in here
                rotis = n + 1     // critical section ends
                mu.Unlock()       // put the chalk back
            }

Real output: expected 1000000, tally says 1000000. Other goroutines still run during Gosched, but none can get past Lock until the holder unlocks.

The memory model's lock rule also guarantees visibility: what one goroutine wrote before Unlock is seen by the next goroutine after Lock.

defer Unlock

A function with several returns can leave without unlocking:

package main

import (
    "fmt"
    "sync"
)

var mu sync.Mutex
var stock = map[string]int{"paneer": 2}

// take one portion; report false if none is left
func take(dish string) bool {
    mu.Lock()
    if stock[dish] == 0 {
        return false // oops: returns while holding the lock
    }
    stock[dish]--
    mu.Unlock()
    return true
}

func main() {
    for order := 1; order <= 4; order++ {
        fmt.Println("order", order, "paneer:", take("paneer"))
    }
}

Real output:

order 1 paneer: true
order 2 paneer: true
order 3 paneer: false
fatal error: all goroutines are asleep - deadlock!

goroutine 1 [sync.Mutex.Lock]:
internal/sync.runtime_SemacquireMutex(0x4930ff?, 0x0?, 0x4b8320?)
    /usr/local/go1.25.1/src/runtime/sema.go:95 +0x25
internal/sync.(*Mutex).lockSlow(0x58d7d8)
    /usr/local/go1.25.1/src/internal/sync/mutex.go:149 +0x15d
...
main.take({0x4bc5c5, 0x6})
    main.go:13 +0x48
main.main()
    main.go:24 +0x32
exit status 2

Order 3 returned with the mutex still locked; order 4's Lock waits forever. Go's mutex is not re-entrant (also called not recursive): even the goroutine that holds it cannot lock it again.

The fix, and the Go habit: defer mu.Unlock() right after mu.Lock().

package main

import (
    "fmt"
    "sync"
)

var mu sync.Mutex
var stock = map[string]int{"paneer": 2}

func take(dish string) bool {
    mu.Lock()
    defer mu.Unlock() // runs on every return path
    if stock[dish] == 0 {
        return false
    }
    stock[dish]--
    return true
}

func main() {
    for order := 1; order <= 4; order++ {
        fmt.Println("order", order, "paneer:", take("paneer"))
    }
}

Real output:

order 1 paneer: true
order 2 paneer: true
order 3 paneer: false
order 4 paneer: false

Unlocking a mutex that isn't locked is fatal too:

var mu sync.Mutex
mu.Unlock()
fatal error: sync: unlock of unlocked mutex

It is a fatal error, not a panic, so recover (episode 26) can't catch it.

sync.RWMutex: many readers, one writer

Reading the menu board changes nothing, so many customers can read together. Only repainting a price needs everyone else out.

Method Lock kind Who may hold it at the same time
RLock / RUnlock read lock any number of readers (no writer)
Lock / Unlock write lock exactly one writer (no readers)
package main

import (
    "fmt"
    "sync"
    "time"
)

var price = map[string]int{"dosa": 60, "idli": 40}

// 10 customers read the menu board; reading takes 100 ms
func readers(lock, unlock func()) time.Duration {
    start := time.Now()
    var wg sync.WaitGroup
    for c := 1; c <= 10; c++ {
        wg.Go(func() {
            lock()
            _ = price["dosa"]
            time.Sleep(100 * time.Millisecond)
            unlock()
        })
    }
    wg.Wait()
    return time.Since(start).Round(10 * time.Millisecond)
}

func main() {
    var mu sync.Mutex
    fmt.Println("Mutex:   ", readers(mu.Lock, mu.Unlock))
    var rw sync.RWMutex
    fmt.Println("RWMutex: ", readers(rw.RLock, rw.RUnlock))

    rw.Lock() // the owner changes a price: a writer is alone
    price["dosa"] = 70
    rw.Unlock()
    fmt.Println("dosa now costs", price["dosa"])
}

Real output:

Mutex:    1s
RWMutex:  100ms
dosa now costs 70

mu.Lock is a method value (episode 20): a method bound to its receiver, passed around as a func().

When to use which: an RWMutex pays off when reads are far more common than writes and the read critical sections are not tiny (caches, configuration, lookup tables). For short, mixed work a plain Mutex is simpler and often as fast. A waiting writer blocks new readers, so writers are not starved, and an RLock must not be upgraded to Lock while held (that deadlocks).

Lock granularity

Lock granularity is how much code a lock covers: coarse = a lot, fine = a little.

package main

import (
    "fmt"
    "sync"
    "time"
)

func cook() { time.Sleep(50 * time.Millisecond) } // slow work

func run(coarse bool) time.Duration {
    var mu sync.Mutex
    served := 0
    start := time.Now()
    var wg sync.WaitGroup
    for c := 1; c <= 10; c++ {
        wg.Go(func() {
            if coarse {
                mu.Lock()
                cook() // cooking while holding the chalk!
                served++
                mu.Unlock()
            } else {
                cook() // cook first, without the lock
                mu.Lock()
                served++ // lock only the shared tally
                mu.Unlock()
            }
        })
    }
    wg.Wait()
    return time.Since(start).Round(10 * time.Millisecond)
}

func main() {
    fmt.Println("lock around everything:", run(true))
    fmt.Println("lock only the tally:   ", run(false))
}

Real output:

lock around everything: 500ms
lock only the tally:    50ms

Rules of thumb: - Lock the shared data, not slow work (network calls, disk writes, sleeps, heavy computation). - But keep together the steps that must be atomic (all-or-nothing as seen by others): a check and the update that depends on it (if stock == 0 … stock--) must stay in one critical section, or you get lost updates again. - One mutex per group of related data is usually enough; very fine locking (many mutexes) invites deadlocks when two locks are taken in different orders.

A mutex inside a struct, and the copied-lock bug

In real code the mutex sits in the struct next to the fields it guards, usually named mu and placed just above them:

// files: go.mod (module shop, go 1.25) and main.go
package main

import (
    "fmt"
    "sync"
)

// Counter keeps its lock right next to the data it guards
type Counter struct {
    mu sync.Mutex
    n  int
}

func (c Counter) Inc() { // value receiver: c is a copy!
    c.mu.Lock()
    defer c.mu.Unlock()
    c.n++
}

func (c *Counter) Value() int {
    c.mu.Lock()
    defer c.mu.Unlock()
    return c.n
}

func main() {
    dosas := &Counter{}
    var wg sync.WaitGroup
    for i := 0; i < 1000; i++ {
        wg.Go(func() { dosas.Inc() })
    }
    wg.Wait()
    fmt.Println("dosas sold:", dosas.Value())
}

Real output of go run . then go vet .:

$ go run .
dosas sold: 0
$ go vet .
# shop
# [shop]
./main.go:14:9: Inc passes lock by value: shop.Counter contains sync.Mutex

A value receiver (episode 20) gets a copy of the struct: a separate mutex and a separate n. All 1000 increments happened on copies that were thrown away. A mutex (and a WaitGroup) must not be copied after first use. The go vet check that finds this is copylocks.

The fix: a pointer receiver.

func (c *Counter) Inc() { // pointer receiver: the real one
    c.mu.Lock()
    defer c.mu.Unlock()
    c.n++
}

Real output:

$ go run .
dosas sold: 1000
$ go vet .

go vet prints nothing. A type that contains a mutex should use pointer receivers for all its methods and be passed around as a pointer.

Other ways to copy a lock that copylocks reports: b := a where a holds a mutex, passing such a struct by value to a function, returning it by value, and for _, v := range over a slice of such structs.

Embedding (episode 23) sync.Mutex in a struct (type T struct { sync.Mutex; ... }) also works but exports Lock and Unlock as methods of your type, so anyone can lock it. Prefer a named, unexported field mu.

Mini project: a safe order counter

Build an Orders type with an RWMutex and a map; 100 goroutines place 100 random orders each; check the total is exactly 10,000.

package main

import (
    "fmt"
    "math/rand/v2"
    "sync"
)

type Orders struct {
    mu     sync.RWMutex
    byDish map[string]int
}

func NewOrders() *Orders { return &Orders{byDish: map[string]int{}} }

func (o *Orders) Add(dish string) {
    o.mu.Lock()
    defer o.mu.Unlock()
    o.byDish[dish]++
}

func (o *Orders) Count(dish string) int {
    o.mu.RLock()
    defer o.mu.RUnlock()
    return o.byDish[dish]
}

// Top returns the best-selling dish and its count
func (o *Orders) Top() (string, int) {
    o.mu.RLock()
    defer o.mu.RUnlock()
    best, n := "", -1
    for d, c := range o.byDish {
        if c > n || (c == n && d < best) {
            best, n = d, c
        }
    }
    return best, n
}

func main() {
    menu := []string{"dosa", "idli", "vada", "poha"}
    o := NewOrders()
    var wg sync.WaitGroup
    for g := 0; g < 100; g++ {
        wg.Go(func() {
            for i := 0; i < 100; i++ {
                o.Add(menu[rand.IntN(len(menu))])
            }
        })
    }
    wg.Wait()
    total := 0
    for _, d := range menu {
        total += o.Count(d)
    }
    dish, n := o.Top()
    fmt.Println("total:", total)
    fmt.Println("top:", dish, n)
}

Real output (the top dish and its count vary because the orders are random):

total: 10000
top: idli 2546

Experiment: delete the Lock/Unlock lines in Add. Many goroutines writing one map at once usually stops the program with fatal error: concurrent map writes (episode 16: maps are not safe for concurrent use).

Common mistakes (and the real messages)

Mistake Real message / result Why Fix
main returns without waiting only shop closed program ends when main returns sync.WaitGroup
time.Sleep as a wait orders 3, 4, 5 lost a guess wg.Wait()
no wg.Done() fatal error: all goroutines are asleep - deadlock! counter never reaches 0 defer wg.Done(), or wg.Go
Done more often than Add panic: sync: negative WaitGroup counter counter below 0 one Done per Add
wg.Add(1) inside the goroutine shop closed with nothing delivered; vet: WaitGroup.Add called from inside new goroutine Wait may see 0 Add before go, or wg.Go
wg.Go with an old go line vet: sync.Go requires go1.25 or later (module is go1.24) API added in Go 1.25 go 1.25 in go.mod, or Add/Done
counter++ from many goroutines expected 1000000, tally says 695792 (sometimes correct by luck) race condition sync.Mutex
return without Unlock fatal error: all goroutines are asleep - deadlock! lock held forever defer mu.Unlock()
locking twice in one goroutine deadlock Go's mutex is not re-entrant restructure, unexported helpers that assume the lock is held
Unlock on an unlocked mutex fatal error: sync: unlock of unlocked mutex unpaired Unlock pair Lock and Unlock
slow work inside the lock lock around everything: 500ms everyone waits in line lock only the shared data
value receiver on a struct with a mutex dosas sold: 0; vet: Inc passes lock by value: shop.Counter contains sync.Mutex lock (and data) copied pointer receivers

Practice

  1. Rewrite the five-delivery program with Add/Done so that deliver doesn't take the WaitGroup at all (hint: a closure in main).
  2. What does this print, and why?
var wg sync.WaitGroup
wg.Wait()
fmt.Println("done")
  1. Make the race program correct without a mutex, using only one goroutine per cook and adding up results in main (hint: give each cook its own slot in a slice).
  2. Why is func (c Counter) Value() int (value receiver, reads only) still a bug if Counter contains a mutex?
  3. (Homework) Run go vet on your last three programs.
Solution 1
package main

import (
    "fmt"
    "sync"
    "time"
)

func deliver(order int) {
    time.Sleep(time.Duration(order) * 100 * time.Millisecond)
    fmt.Println("order", order, "delivered")
}

func main() {
    var wg sync.WaitGroup
    for order := 1; order <= 5; order++ {
        wg.Add(1)
        go func() {
            defer wg.Done()
            deliver(order)
        }()
    }
    wg.Wait()
    fmt.Println("shop closed")
}

deliver no longer knows about concurrency: the caller decides how to run and wait for it. This is a good design habit.

Solution 2

done. The counter is already 0, so Wait returns at once.

Solution 3
package main

import (
    "fmt"
    "sync"
)

func main() {
    perCook := make([]int, 1000) // each cook writes only its own slot
    var wg sync.WaitGroup
    for cook := 0; cook < 1000; cook++ {
        wg.Go(func() {
            for i := 0; i < 1000; i++ {
                perCook[cook]++
            }
        })
    }
    wg.Wait() // all writes happen before Wait returns
    total := 0
    for _, n := range perCook {
        total += n
    }
    fmt.Println("tally says", total)
}

Real output: tally says 1000000. Different slice elements are different variables, so there is no data race, and wg.Wait() makes every write visible to main.

Solution 4

The value receiver copies the struct, including the mutex, while another goroutine may be writing it: the copy itself is an unsynchronised read of n and of the mutex state. go vet reports Value passes lock by value. Use func (c *Counter) Value() int.

Quick quiz

1. Three wg.Add(1), three goroutines doing n++ with no Done, then wg.Wait() and fmt.Println(n). What happens? (From the video.)

A. 3 · B. 0 · C. fatal error: all goroutines are asleep - deadlock! · D. panic: sync: negative WaitGroup counter

Answer

C. Nobody calls Done, so Wait blocks forever. (And even with Done, n++ from three goroutines would be a data race.)

2. Where must wg.Add(1) go?

Answer

Before the go statement, in the goroutine that will call Wait (or use wg.Go, which does it for you).

3. Ten goroutines hold a plain Mutex for 100 ms each. How long does it take? And with RLock on an RWMutex?

Answer

About 1 s (one after another), and about 100 ms (all readers together).

4. Is sync.Mutex re-entrant?

Answer

No. Locking it twice in the same goroutine without unlocking deadlocks.

Interview questions

  1. What is a WaitGroup and how do you use it? A counter of running goroutines: Add before go, Done at the end (usually deferred), Wait blocks until zero. Go 1.25 adds wg.Go(f).
  2. Why must Add be called before the go statement? Otherwise Wait can run before the goroutine's Add and see 0. go vet (Go 1.25) reports Add inside a new goroutine.
  3. What is a race condition? A data race? A race condition: correctness depends on timing. A data race: two goroutines access the same variable concurrently, at least one writes, no synchronisation. Most race conditions in Go code are data races.
  4. Why is x++ not safe from many goroutines? It is read, add, write; interleavings lose updates.
  5. What is a critical section? Code that accesses shared data; only one goroutine may be inside at a time.
  6. Mutex vs RWMutex? Mutex: one holder. RWMutex: many readers or one writer. Use RWMutex for read-heavy data with non-trivial read sections.
  7. Why defer mu.Unlock()? It unlocks on every return path and on panic; forgetting an Unlock deadlocks.
  8. Is Go's Mutex re-entrant? No.
  9. What is lock granularity? How much code a lock covers. Lock only shared data, keep dependent steps together, avoid slow work under a lock.
  10. Why can't you copy a Mutex? How do you catch it? A copy is an independent lock, so the original data is unprotected. go vet copylocks: "passes lock by value". Use pointer receivers.
  11. What does fatal error: all goroutines are asleep - deadlock! mean? Every goroutine is blocked forever (a channel, a lock, Wait), so the runtime stops the program.

Glossary

Term Meaning Example
Goroutine a lightweight function running concurrently, started with go go deliver(1)
Synchronisation making goroutines coordinate: wait for each other or take turns wg.Wait(), mu.Lock()
sync package Go's standard package of synchronisation tools sync.WaitGroup, sync.Mutex
sync.WaitGroup a counter that lets one goroutine wait for others var wg sync.WaitGroup
Add changes the WaitGroup counter by a number wg.Add(1)
Done lowers the counter by 1 (Add(-1)) defer wg.Done()
Wait blocks until the counter is 0 wg.Wait()
WaitGroup.Go Go 1.25: Add(1), start f in a goroutine, Done when it returns wg.Go(func() { ... })
Block stop at a line and sleep until a condition is met Wait, Lock
Zero value the value a variable has before you set it; for WaitGroup and Mutex, ready to use var mu sync.Mutex (unlocked)
Deadlock goroutines waiting for something that can never happen fatal error: all goroutines are asleep - deadlock!
Negative WaitGroup counter more Done calls than Add panic: sync: negative WaitGroup counter
go vet Go's static checker for suspicious code go vet .
waitgroup analyzer vet check (Go 1.25) for misplaced Add WaitGroup.Add called from inside new goroutine
Race condition a bug where the result depends on goroutine timing the tally says 695792
Data race two goroutines, same variable, at least one write, no synchronisation rotis++ in 1000 goroutines
Lost update an increment overwritten by another, so it never counts both cooks write 42
Critical section code that reads or writes shared data; one goroutine at a time rotis++ between Lock and Unlock
Mutual exclusion keeping all others out while one goroutine is inside one piece of chalk
Mutex (sync.Mutex) a mutual-exclusion lock mu.Lock(); ...; mu.Unlock()
Lock / Unlock take / release a mutex (Lock blocks while it's held) mu.Lock()
defer mu.Unlock() release the lock when the function returns, on every path right after mu.Lock()
Re-entrant lock a lock its holder can take again; Go's mutex is not double Lock → deadlock
Unlock of unlocked mutex Unlock with no Lock held fatal error: sync: unlock of unlocked mutex
sync.RWMutex reader/writer lock: many readers or one writer rw.RLock()
RLock / RUnlock take / release the read lock readers of a cache
Lock granularity how much code a lock covers (coarse vs fine) 500ms vs 50ms
Atomic (steps) all-or-nothing as seen by other goroutines check-and-decrement stock
Method value a method bound to its receiver, used as a function mu.Lock passed as func()
Value receiver a method that gets a copy of the struct func (c Counter) Inc()
Pointer receiver a method that gets a pointer to the real struct func (c *Counter) Inc()
Copied lock a mutex copied after use: a separate, useless lock Inc passes lock by value
copylocks the go vet check that reports copied locks go vet .
fatal error: concurrent map writes the runtime stops a program that writes a map from several goroutines map without a lock

Summary

  • When main returns, every goroutine dies; sleeping a guess is not waiting.
  • sync.WaitGroup: Add(1) before go, defer Done() in the goroutine, Wait() until zero. Go 1.25: wg.Go(f) does all three.
  • WaitGroup mistakes: forgotten Done (deadlock), extra Done (negative counter panic), Add inside the goroutine (Wait returns early; vet reports it).
  • A race condition silently loses updates; x++ is read, add, write.
  • Guard the critical section with sync.Mutex: mu.Lock(); defer mu.Unlock(). Go's mutex is not re-entrant.
  • sync.RWMutex: RLock for many readers together, Lock for one writer.
  • Lock granularity: lock data, not slow work; keep dependent steps together.
  • Put the mutex next to its data in a struct, use pointer receivers, never copy a lock; go vet copylocks finds copies.

Next episode: The race detector and the Go memory model: go run -race, reading race reports, happens-before, synchronising operations, why "benign" races are not benign, and -race in CI.