SyntaxPilot
Courses/Go Programming/Lesson 50
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 50 of 89

sync beyond Mutex, and atomics

sync.Oncesync.OnceFuncsync.OnceValuesync.Cond (Wait, Signal, Broadcast)sync.Map and when to use itsync.Poolsync/atomicatomic.Int64atomic.Boolatomic.Pointeratomic.ValueLoadStoreAdd

These are the notes for Go episode 50. Five waiters ask for the menu at the same moment and it is loaded 5 times: you invent sync.Once (and the Go 1.21 shortcuts OnceValue and OnceFunc). Cooks waiting for a hot tandoor need a condition variable, sync.Cond, where Signal wakes one and Broadcast wakes all. Two goroutines writing a plain map crash with fatal error: concurrent map writes, which leads to sync.Map and to when not to use it. A rack of steel plates becomes sync.Pool. Then atomics: a shared counter loses almost every update until it becomes an atomic.Int64, flags and config pointers are swapped with atomic.Bool and atomic.Pointer, the biggest bill is kept with a CompareAndSwap loop, and two counters on one cache line slow each other down: false sharing.

All outputs and errors here are from real runs (Go 1.24.7, linux/amd64, a machine with 2 CPUs). Timings, counts and the order of some lines change between runs.

Facts and sources

From the official package documentation, pkg.go.dev/sync and pkg.go.dev/sync/atomic:

  • "Once is an object that will perform exactly one action." "If f panics, Do considers it to have returned; future calls of Do return without calling f."
  • OnceFunc, OnceValue and OnceValues were added in Go 1.21. OnceValue "returns a function that invokes f only once and returns the value returned by f."
  • Cond: "For many simple use cases, users will be better off using channels than a Cond."
  • Map: "Most code should use a plain Go map instead, with separate locking or coordination." It is optimised for "(1) when the entry for a given key is only ever written once but read many times, as in caches that only grow" and "(2) when multiple goroutines read, write, and overwrite entries for disjoint sets of keys."
  • Pool: "A Pool is a set of temporary objects that may be individually saved and retrieved." "Any item stored in the Pool may be removed automatically at any time without notification."
  • sync/atomic: "These functions require great care to be used correctly." and "Share memory by communicating; don't communicate by sharing memory." The types Int64, Bool and Pointer were added in Go 1.19. "A Value provides an atomic load and store of a consistently typed value."

sync.Once: exactly once

At Raju's restaurant In Go
the menu is in the back room, slow to fetch an expensive setup step
fetch it only when someone first asks lazy initialisation
5 waiters each see "no menu yet" and fetch it check-then-act race
the first fetches, the rest wait for it sync.Once
package main

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

var menu []string
var loads int

func loadMenu() []string { // slow: reads the menu from disk
    loads++
    time.Sleep(10 * time.Millisecond)
    return []string{"dosa", "idli", "vada"}
}

func getMenu() []string {
    if menu == nil { // "has anybody loaded it yet?"
        menu = loadMenu()
    }
    return menu
}

func main() {
    var wg sync.WaitGroup
    for i := 0; i < 5; i++ { // 5 waiters ask for the menu at once
        wg.Add(1)
        go func() { defer wg.Done(); getMenu() }()
    }
    wg.Wait()
    fmt.Println("menu loaded", loads, "times")
}

Real output:

menu loaded 5 times

The check (menu == nil) and the action (menu = loadMenu()) are separate steps, so all five goroutines passed the check before anyone finished loading. It's also a data race on menu (episode 46's race detector reports it). A mutex around the check works, but every read forever pays for the lock.

once.Do(f) runs f exactly once, however many goroutines call it; callers arriving while f runs wait for it to finish; later calls return immediately.

package main

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

var menu []string
var loads int
var once sync.Once

func loadMenu() []string { // slow: reads the menu from disk
    loads++
    time.Sleep(10 * time.Millisecond)
    return []string{"dosa", "idli", "vada"}
}

func getMenu() []string {
    once.Do(func() { menu = loadMenu() }) // runs exactly once
    return menu
}

func main() {
    var wg sync.WaitGroup
    for i := 0; i < 5; i++ { // 5 waiters ask for the menu at once
        wg.Add(1)
        go func() { defer wg.Done(); getMenu() }()
    }
    wg.Wait()
    fmt.Println("menu loaded", loads, "times")
}

Real output:

menu loaded 1 times

OnceValue and OnceFunc (Go 1.21)

package main

import (
    "fmt"
    "sync"
)

// OnceValue: a function that computes its result only the first time
var getMenu = sync.OnceValue(func() []string {
    fmt.Println("(loading the menu...)")
    return []string{"dosa", "idli", "vada"}
})

// OnceFunc: a function whose body runs only the first time
var lightStove = sync.OnceFunc(func() {
    fmt.Println("(stove lit)")
})

func main() {
    for i := 1; i <= 3; i++ {
        lightStove()
        fmt.Println("order", i, "from", getMenu())
    }
}

Real output:

(stove lit)
(loading the menu...)
order 1 from [dosa idli vada]
order 2 from [dosa idli vada]
order 3 from [dosa idli vada]
Tool Gives you Use for
var once sync.Once; once.Do(f) runs f once any one-time setup
sync.OnceFunc(f) a func() that runs f once one-time actions (light the stove, print a banner)
sync.OnceValue(f) a func() T that computes once and returns the saved value lazily loaded config, menus, tables
sync.OnceValues(f) a func() (T, error) one-time loads that can fail

Panics: if f panics, a plain Once counts it as done and never retries; the OnceFunc/OnceValue(s) wrappers re-panic with the same value on every call. Errors from OnceValues are also remembered: it doesn't retry.

sync.Cond: waiting for a condition

In Raju's kitchen In Go
naan needs a hot tandoor: a state, not a delivered thing a condition on shared state (hot == true), guarded by a mutex
cooks sit and wait, no checking every second cond.Wait(): unlock, sleep, re-lock when woken
"it's hot!" to one cook, or to all cond.Signal() / cond.Broadcast()

A condition variable is a place where goroutines wait until some condition on shared state might have become true. sync.NewCond(&mu) ties it to the mutex that guards the state. Always wait in a for loop that re-checks the condition: after waking, another goroutine may have changed things again.

package main

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

func main() {
    var mu sync.Mutex
    hot := false // the tandoor's state, guarded by mu
    cond := sync.NewCond(&mu)
    var wg sync.WaitGroup
    for i := 1; i <= 3; i++ {
        wg.Add(1)
        go func() {
            defer wg.Done()
            mu.Lock()
            for !hot { // check the condition, under the lock
                cond.Wait() // unlock, sleep, re-lock when woken
            }
            mu.Unlock()
            fmt.Println("cook", i, "puts naan in the tandoor")
        }()
    }
    time.Sleep(100 * time.Millisecond) // heating up...
    mu.Lock()
    hot = true
    mu.Unlock()
    cond.Signal() // wake ONE waiting cook
    wg.Wait()
}

Real output:

cook 3 puts naan in the tandoor
fatal error: all goroutines are asleep - deadlock!

goroutine 1 [sync.WaitGroup.Wait]:
sync.runtime_SemacquireWaitGroup(0x477d6f?)
sync.(*WaitGroup).Wait(0x5f5e100?)
main.main()
    main.go:31 +0x1b9

goroutine 18 [sync.Cond.Wait]:
sync.runtime_notifyListWait(0xc00011c0d0, 0x1)
sync.(*Cond).Wait(0x0?)
main.main.func1()
    main.go:20 +0xb9
created by main.main in goroutine 1
    main.go:16 +0xb4

goroutine 19 [sync.Cond.Wait]:
sync.runtime_notifyListWait(0xc00011c0d0, 0x2)
sync.(*Cond).Wait(0x0?)
main.main.func1()
    main.go:20 +0xb9
...

Signal wakes exactly one waiter. With Broadcast:

package main

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

func main() {
    var mu sync.Mutex
    hot := false // the tandoor's state, guarded by mu
    cond := sync.NewCond(&mu)
    var wg sync.WaitGroup
    for i := 1; i <= 3; i++ {
        wg.Add(1)
        go func() {
            defer wg.Done()
            mu.Lock()
            for !hot { // check the condition, under the lock
                cond.Wait() // unlock, sleep, re-lock when woken
            }
            mu.Unlock()
            fmt.Println("cook", i, "puts naan in the tandoor")
        }()
    }
    time.Sleep(100 * time.Millisecond) // heating up...
    mu.Lock()
    hot = true
    mu.Unlock()
    cond.Broadcast() // wake EVERY waiting cook
    wg.Wait()
}

Real output (any order):

cook 2 puts naan in the tandoor
cook 3 puts naan in the tandoor
cook 1 puts naan in the tandoor
close(ch) (episode 48) cond.Broadcast()
wakes every receiver every waiter
repeatable no: only once yes, every time the state changes
works with select/timeouts yes no

The docs advise channels for most simple cases; Cond fits when many goroutines wait on a state that changes repeatedly.

Maps and goroutines: sync.Map

A plain map (episode 15/16) is not safe for concurrent use:

package main

import (
    "fmt"
    "sync"
)

func main() {
    stock := map[string]int{} // a plain map, shared
    var wg sync.WaitGroup
    for _, cook := range []string{"Raju", "Asha"} {
        wg.Add(1)
        go func() {
            defer wg.Done()
            for i := 0; i < 100000; i++ {
                stock[fmt.Sprint(cook, i%100)]++
            }
        }()
    }
    wg.Wait()
    fmt.Println("items:", len(stock))
}

Real output (start of the report):

fatal error: concurrent map writes

goroutine 19 [running]:
internal/runtime/maps.fatal({0x4b8071?, 0x466472?})
main.main.func1()
    main.go:16 +0xf2
created by main.main in goroutine 1
    main.go:13 +0x9c

goroutine 1 [sync.WaitGroup.Wait]:
sync.runtime_SemacquireWaitGroup(0xc000118150?)
sync.(*WaitGroup).Wait(0x7f9d7de5efe8?)
main.main()
    main.go:20 +0x14c

goroutine 18 [runnable]:
main.main.func1()
    main.go:16 +0x7f
created by main.main in goroutine 1
    main.go:13 +0x9c
exit status 2

This is a fatal error, not a panic: recover cannot catch it. The default fix is a map plus a sync.Mutex (see practice 2).

sync.Map is a map that is safe for concurrent use without your own lock. Keys and values have type any.

Method Does
Load(k) returns (value, ok)
Store(k, v) sets the value
LoadOrStore(k, v) returns the existing value (loaded == true), or stores v (loaded == false)
LoadAndDelete(k), Delete(k) removes the key
Swap(k, v), CompareAndSwap(k, old, new) atomic updates of one entry
Range(f) calls f(k, v) for each entry until f returns false
Clear() removes everything (Go 1.23)
package main

import (
    "fmt"
    "sync"
)

func main() {
    var prices sync.Map // safe for concurrent use, no lock needed
    var wg sync.WaitGroup
    for _, d := range []string{"dosa", "idli", "vada", "dosa"} {
        wg.Add(1)
        go func() {
            defer wg.Done()
            // store a price only if nobody stored one yet
            v, loaded := prices.LoadOrStore(d, 40)
            fmt.Println(d, "=", v, "already there:", loaded)
        }()
    }
    wg.Wait()
    prices.Store("vada", 30) // overwrite
    p, ok := prices.Load("vada")
    fmt.Println("vada now", p, ok)
    prices.Range(func(k, v any) bool { // visit every entry
        fmt.Println(" ", k, v)
        return true // keep going
    })
}

Real output (the order of goroutine lines and of Range changes):

dosa = 40 already there: false
idli = 40 already there: false
vada = 40 already there: false
dosa = 40 already there: true
vada now 30 true
  idli 40
  dosa 40
  vada 30

When to use it: keys written once and read many times (grow-only caches), or goroutines working on disjoint keys. Otherwise a plain map with a mutex is simpler, type-safe and usually faster.

sync.Pool: reusable temporary objects

In Raju's kitchen In Go
a rack of steel plates instead of new paper plates sync.Pool
take a plate, wash it, use it, put it back Get, reset, use, Put; New makes one if the pool is empty
the cleaner may clear the rack at any time the garbage collector may empty the pool

An allocation is reserving new memory for an object; the garbage collector must later free it. A pool lets hot code reuse objects instead. bytes.Buffer is the standard library's growable byte buffer.

package main

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

func main() {
    made := 0
    plates := sync.Pool{ // a rack of reusable steel plates
        New: func() any { made++; return new(bytes.Buffer) },
    }
    for i := 0; i < 1000; i++ { // 1000 orders, one after another
        b := plates.Get().(*bytes.Buffer)
        b.Reset() // wash it first
        fmt.Fprintf(b, "order %d", i)
        plates.Put(b) // back on the rack
    }
    fmt.Println("1000 orders, plates made:", made)

    runtime.GC() // the cleaner may clear the rack at any time
    runtime.GC()
    plates.Get()
    fmt.Println("after GC, plates made:", made)
}

Real output:

1000 orders, plates made: 1
after GC, plates made: 2

Rules: always reset an object you Get; never keep anything you need in a pool; store pointers (like *bytes.Buffer), not large values. The fmt package keeps its printers in a pool.

Atomic operations

At Raju's counter In Go
a tally on a whiteboard: read, add one, write x++: three steps, others slip in
a token machine: one press, the next number an atomic operation: one indivisible step
nobody waits for a key lock-free

An atomic operation is one that no other goroutine can ever see half done. sync/atomic provides them; the typed versions (Go 1.19) are the easiest to use correctly:

Type Methods
atomic.Int32, Int64, Uint32, Uint64, Uintptr Load, Store, Add, Swap, CompareAndSwap (and And/Or since Go 1.23)
atomic.Bool Load, Store, Swap, CompareAndSwap
atomic.Pointer[T] Load, Store, Swap, CompareAndSwap on a *T
atomic.Value Load, Store, Swap, CompareAndSwap on any (one consistent type)
package main

import (
    "fmt"
    "runtime"
    "sync"
    "sync/atomic"
)

func main() {
    plain := 0              // a normal int, shared
    var orders atomic.Int64 // an atomic int: no lock needed
    var wg sync.WaitGroup
    for c := 0; c < 100; c++ { // 100 billing counters
        wg.Add(1)
        go func() {
            defer wg.Done()
            for i := 0; i < 1000; i++ {
                n := plain        // plain++ is three steps: read...
                runtime.Gosched() // (another goroutine runs here)
                plain = n + 1     // ...add, write
                orders.Add(1)     // one indivisible step
            }
        }()
    }
    wg.Wait()
    fmt.Println("expected:    ", 100*1000)
    fmt.Println("plain int:   ", plain)
    fmt.Println("atomic.Int64:", orders.Load())
}

Real output (the plain count changes every run):

expected:     100000
plain int:    1113
atomic.Int64: 100000

An atomic add is a single CPU instruction, so it is usually cheaper than a mutex Lock/Unlock pair, but measure on your own machine (benchmarks, episode 42). Atomics protect one value. If two values must change together (stock and bill), use a mutex.

Bool, Pointer and Value

package main

import (
    "fmt"
    "sync/atomic"
)

type Menu struct {
    Items []string
    Price int
}

func main() {
    var open atomic.Bool
    open.Store(true)
    fmt.Println("shop open:", open.Load())

    var menu atomic.Pointer[Menu] // a pointer that is read and swapped atomically
    menu.Store(&Menu{[]string{"dosa", "idli"}, 40})
    m := menu.Load() // readers get a whole, consistent menu
    fmt.Println("menu:", m.Items, m.Price)

    old := menu.Swap(&Menu{[]string{"dosa", "idli", "vada"}, 45}) // publish a new one
    fmt.Println("old:", old.Items, "new:", menu.Load().Items, menu.Load().Price)

    var v atomic.Value // the older, untyped version
    v.Store("dosa")
    v.Store(40) // a different type...
}

Real output:

shop open: true
menu: [dosa idli] 40
old: [dosa idli] new: [dosa idli vada] 45
panic: sync/atomic: store of inconsistently typed value into Value

goroutine 1 [running]:
sync/atomic.(*Value).Store(0xc0001180b0, {0x49c980, 0x4dafc8})
main.main()
    main.go:28 +0x3c7
exit status 2

atomic.Pointer[Menu] lets many readers Load a complete, consistent menu while a writer publishes a new one with Store/Swap: a common way to hot-swap configuration. atomic.Value is the older untyped form; it panics if you store a different type. Prefer the typed versions.

CompareAndSwap and lock-free code

CompareAndSwap (CAS) sets a new value only if the current value still equals the old value you saw, and reports whether it did, all in one atomic step. A loop around it (load, compute, CAS, retry on failure) updates a value with no lock: lock-free code.

package main

import (
    "fmt"
    "sync"
    "sync/atomic"
)

func main() {
    var highest atomic.Int64 // the biggest bill of the day
    var wg sync.WaitGroup
    for _, bills := range [][]int64{{120, 990, 40}, {300, 1250, 80}, {760, 15}} {
        wg.Add(1)
        go func() {
            defer wg.Done()
            for _, b := range bills {
                for { // the compare-and-swap loop
                    old := highest.Load()
                    if b <= old || highest.CompareAndSwap(old, b) {
                        break // not bigger, or we swapped it in
                    }
                    // someone changed it between Load and CAS: try again
                }
            }
        }()
    }
    wg.Wait()
    fmt.Println("highest bill:", highest.Load())
}

Real output:

highest bill: 1250
package main

import (
    "fmt"
    "sync/atomic"
)

func main() {
    var n atomic.Int64
    n.Store(5)
    ok1 := n.CompareAndSwap(5, 9)
    ok2 := n.CompareAndSwap(5, 7)
    fmt.Println(n.Load(), ok1, ok2)
    fmt.Println("swap returned", n.Swap(1), "now", n.Load())
}

Real output:

9 true false
swap returned 9 now 1

Lock-free code never deadlocks, but it's hard to get right beyond single values. Use it for counters, maximums, flags and pointer swaps.

False sharing

A CPU cache is a small, very fast copy of recently used memory, kept per core. It moves memory in blocks called cache lines, usually 64 bytes. When two cores write different variables on the same line, the line bounces between their caches: false sharing (sharing a cache line, not data). Padding (unused bytes) puts each hot variable on its own line.

At Raju's counter Inside the CPU
two cashiers, separate totals, same notebook page two counters on one cache line
they keep passing the notebook the line moves between cores
a separate page each padding
package main

import (
    "fmt"
    "sync"
    "sync/atomic"
    "time"
)

type Close struct{ a, b atomic.Int64 }                // side by side in memory
type Apart struct{ a atomic.Int64; _ [56]byte; b atomic.Int64 } // 56 bytes of padding: b on another 64-byte line

func race(a, b *atomic.Int64) time.Duration {
    start := time.Now()
    var wg sync.WaitGroup
    for _, c := range []*atomic.Int64{a, b} { // each goroutine has its OWN counter
        wg.Add(1)
        go func() {
            defer wg.Done()
            for i := 0; i < 20_000_000; i++ {
                c.Add(1)
            }
        }()
    }
    wg.Wait()
    return time.Since(start).Round(time.Millisecond)
}

func main() {
    var c, p = Close{}, Apart{}
    bestC, bestP := time.Hour, time.Hour
    for round := 1; round <= 7; round++ { // best of 7: ignore noisy runs
        bestC = min(bestC, race(&c.a, &c.b))
        bestP = min(bestP, race(&p.a, &p.b))
    }
    fmt.Println("best of 7, side by side:", bestC)
    fmt.Println("best of 7, padded apart:", bestP)
}

main keeps the best of 7 runs of each layout (min is a built-in function since Go 1.21), so one noisy run can't hide the effect. Real output (times vary; on a busy machine the gap shrinks):

best of 7, side by side: 738ms
best of 7, padded apart: 95ms

Measure before padding anything (benchmarks, episode 42; profiling, episode 57). The fieldalignment analyser (in golang.org/x/tools) and unsafe.Offsetof (episode 55) help you see struct layout.

Mini project: the token counter

50 customers take tokens (atomic.Int64.Add), a Once opens the counter, a CAS loop keeps the longest wait, a Pool of buffers formats receipts, and a sync.Map of *atomic.Int64 counts dishes.

package main

import (
    "bytes"
    "fmt"
    "math/rand/v2"
    "sync"
    "sync/atomic"
    "time"
)

func main() {
    var next atomic.Int64    // token numbers
    var longest atomic.Int64 // longest wait, in microseconds
    var open sync.Once
    var stats sync.Map // dish -> *atomic.Int64
    buffers := sync.Pool{New: func() any { return new(bytes.Buffer) }}
    dishes := []string{"chai", "dosa", "idli"}

    var wg sync.WaitGroup
    for c := 0; c < 50; c++ {
        wg.Add(1)
        go func() {
            defer wg.Done()
            arrived := time.Now()
            open.Do(func() { fmt.Println("counter open") })
            token := next.Add(1)
            time.Sleep(time.Duration(rand.IntN(3000)) * time.Microsecond) // waiting
            wait := time.Since(arrived).Microseconds()
            for { // CAS loop: keep the maximum
                old := longest.Load()
                if wait <= old || longest.CompareAndSwap(old, wait) {
                    break
                }
            }
            dish := dishes[token%3]
            n, _ := stats.LoadOrStore(dish, new(atomic.Int64))
            n.(*atomic.Int64).Add(1)

            b := buffers.Get().(*bytes.Buffer)
            b.Reset()
            fmt.Fprintf(b, "token %d: %s", token, dish)
            _ = b.String() // the receipt
            buffers.Put(b)
        }()
    }
    wg.Wait()
    fmt.Println("tokens issued:", next.Load())
    fmt.Println("longest wait under 10ms:", longest.Load() < 10_000)
    stats.Range(func(k, v any) bool {
        fmt.Println(" ", k, v.(*atomic.Int64).Load())
        return true
    })
}

Real output (counts per dish and the order vary):

counter open
tokens issued: 50
longest wait under 10ms: true
  dosa 17
  idli 17
  chai 16

Common mistakes (and the real messages)

Mistake Real message / result Why Fix
if x == nil { x = load() } from many goroutines menu loaded 5 times (and a data race) check-then-act sync.Once / OnceValue
cond.Wait() without a for loop wakes with the condition false spurious or stale wake-ups for !cond { c.Wait() }
Signal with several waiters deadlock! [sync.Cond.Wait] wakes one Broadcast
two goroutines writing a plain map fatal error: concurrent map writes maps aren't safe map + Mutex, or sync.Map
sync.Map everywhere slower, untyped code built for 2 special cases map + Mutex
keeping data in a Pool objects vanish after GC pools are caches real storage elsewhere
forgetting to reset a pooled object old data leaks into new output it's reused b.Reset() after Get
shared x++ plain int: 1006 three steps atomic.Int64.Add
two related values in two atomics inconsistent snapshots not updated together Mutex
atomic.Value with a new type panic: sync/atomic: store of inconsistently typed value into Value one type only atomic.Pointer[T]
copying a sync.Once, Cond, Mutex or atomic type after use broken synchronisation (go vet copylocks) they must not be copied pass pointers

Practice

  1. Load a menu that can fail with sync.OnceValues. What happens on the second call?
  2. Rewrite the concurrent-map program safely with a map and a mutex.
  3. A once.Do function panics. Does a second Do run it again?
  4. Predict: n.Store(5), CompareAndSwap(5, 9), CompareAndSwap(5, 7), then Swap(1).
Solutions

1.

package main

import (
    "errors"
    "fmt"
    "sync"
)

var loadMenu = sync.OnceValues(func() ([]string, error) {
    fmt.Println("(reading menu.txt...)")
    return nil, errors.New("menu.txt: file not found")
})

func main() {
    for i := 0; i < 2; i++ {
        menu, err := loadMenu()
        fmt.Println(menu, err)
    }
}

Real output:

(reading menu.txt...)
[] menu.txt: file not found
[] menu.txt: file not found

The function ran once; the error is remembered and returned again without retrying.

2.

package main

import (
    "fmt"
    "sync"
)

type Stock struct {
    mu    sync.Mutex
    count map[string]int
}

func (s *Stock) Add(item string) {
    s.mu.Lock()
    defer s.mu.Unlock()
    s.count[item]++
}

func main() {
    s := Stock{count: map[string]int{}}
    var wg sync.WaitGroup
    for _, cook := range []string{"Raju", "Asha"} {
        wg.Add(1)
        go func() {
            defer wg.Done()
            for i := 0; i < 100000; i++ {
                s.Add(fmt.Sprint(cook, i%100))
            }
        }()
    }
    wg.Wait()
    fmt.Println("items:", len(s.count), "Raju0:", s.count["Raju0"])
}

Real output:

items: 200 Raju0: 1000

3.

package main

import (
    "fmt"
    "sync"
)

func main() {
    var once sync.Once
    for i := 1; i <= 2; i++ {
        func() {
            defer func() { recover() }()
            once.Do(func() {
                fmt.Println("try", i, "loading...")
                panic("disk error")
            })
            fmt.Println("try", i, "Do returned without running f")
        }()
    }
}

Real output:

try 1 loading...
try 2 Do returned without running f

No: "If f panics, Do considers it to have returned."

4. See the p4.go program and output in the CompareAndSwap section: 9 true false, then swap returned 9 now 1.

Quick quiz

1. n.Store(5); ok1 := n.CompareAndSwap(5, 9); ok2 := n.CompareAndSwap(5, 7); fmt.Println(n.Load(), ok1, ok2) (From the video.)

A. 9 true false · B. 7 true true · C. 9 true true · D. 5 false false

Answer

A. The first CAS sees 5 and stores 9; the second expects 5, finds 9, and changes nothing.

2. Five goroutines call once.Do(load) at the same time. How many times does load run, and do the others wait?

Answer

Once. The others block until it returns, then return without calling it.

3. Why must cond.Wait() be called in a for loop?

Answer

When a goroutine wakes, the condition may no longer be true (another goroutine changed it first), so it must re-check.

4. Can recover catch fatal error: concurrent map writes?

Answer

No. It's a fatal runtime error, not a panic.

Interview questions

  1. How do you initialise something exactly once, safely? sync.Once, or sync.OnceValue/OnceValues/OnceFunc (Go 1.21).
  2. What is sync.Cond and when would you use it over channels? A condition variable tied to a mutex: Wait (in a loop), Signal, Broadcast. Use it when many goroutines wait on a shared state that changes repeatedly; channels are simpler for one-off events.
  3. Is a Go map safe for concurrent use? No; concurrent writes (or a write with reads) can crash with a fatal error. Use a mutex or sync.Map.
  4. When is sync.Map a good choice? Grow-only caches (write once, read many) and disjoint key sets per goroutine. Otherwise prefer map + Mutex.
  5. What is sync.Pool for, and what's its main caveat? Reusing temporary objects to cut allocations in hot paths; the GC can empty it at any time, so it's not storage.
  6. Atomic vs mutex? Atomics: one value, one indivisible operation, lock-free, fast. Mutex: any amount of state changed together.
  7. What is CAS and how do you use it? CompareAndSwap sets a value only if it still equals the expected old value; loop: load, compute, CAS, retry.
  8. What's the difference between atomic.Value and atomic.Pointer[T]? Value stores any and panics on inconsistent types; Pointer[T] is type-checked at compile time.
  9. What is false sharing? Independent variables on the same cache line written by different cores, forcing the line to bounce between caches; fixed with padding or separate allocation.

Glossary

Term Meaning Example
Lazy initialisation setting something up when it's first needed load the menu on the first request
Check-then-act checking a condition, then acting on it, as two steps (racy if shared) if menu == nil { menu = load() }
sync.Once runs a function exactly once once.Do(load)
sync.OnceFunc wraps a func() to run once lightStove := sync.OnceFunc(f)
sync.OnceValue wraps a func() T: computes once, returns the saved value getMenu := sync.OnceValue(f)
sync.OnceValues like OnceValue for (T, error) loading a file once
Condition variable a place goroutines wait until a condition might be true sync.Cond
cond.Wait unlock, sleep until woken, re-lock for !hot { cond.Wait() }
cond.Signal wakes one waiting goroutine one cook
cond.Broadcast wakes all waiting goroutines all cooks
Fatal error a runtime failure recover can't catch concurrent map writes
sync.Map a concurrency-safe map of any to any prices.LoadOrStore("dosa", 40)
LoadOrStore get the existing value or store a new one, atomically loaded == true
Range visit every entry of a sync.Map prices.Range(func(k, v any) bool {...})
sync.Pool a set of reusable temporary objects plates
Get / Put / New take / return / create a pooled object plates.Get().(*bytes.Buffer)
Allocation reserving new memory for an object new(bytes.Buffer)
bytes.Buffer a growable byte buffer fmt.Fprintf(b, ...)
Atomic operation an operation no goroutine can see half done orders.Add(1)
sync/atomic the package of atomic operations and types atomic.Int64
atomic.Int64 an int64 with atomic methods Load, Store, Add
Load / Store atomic read / write highest.Load()
Add atomic add, returns the new value next.Add(1)
Swap atomic set, returns the old value menu.Swap(newMenu)
CompareAndSwap (CAS) set only if the current value equals the expected old one CompareAndSwap(5, 9)
CAS loop load, compute, CAS, retry until it succeeds highest bill
Lock-free correct concurrent code with no locks; nobody waits for an unlock atomic counters
atomic.Bool a bool with atomic methods open.Store(true)
atomic.Pointer[T] a *T read and replaced atomically hot-swapping a menu
atomic.Value untyped atomic box for one consistent type v.Store("dosa")
CPU cache a small, fast per-core copy of recent memory L1 cache
Cache line the 64-byte block caches move as a unit two counters on one line
False sharing cores slowing each other by writing different values on one cache line side by side slower than padded apart
Padding unused bytes that separate fields _ [56]byte

Summary

  • sync.Once / OnceValue / OnceFunc: exactly-once setup without check-then-act races.
  • sync.Cond: wait in a for loop on shared state; Signal wakes one, Broadcast all; channels are often simpler.
  • A plain map with concurrent writers is a fatal error; default to map + Mutex; sync.Map for grow-only caches and disjoint keys.
  • sync.Pool reuses temporary objects; reset them; the GC may empty it.
  • Atomics (atomic.Int64, Bool, Pointer[T], Value): Load, Store, Add, Swap, CompareAndSwap, lock-free, for single values; a CAS loop builds lock-free updates.
  • False sharing: hot values on one 64-byte cache line slow each other; measure, then pad.

Next episode: context: cancellation, deadlines and values: context.Background, WithCancel, WithTimeout, WithDeadline, WithValue, Done, Err, cancellation trees, WithCancelCause, AfterFunc, WithoutCancel, and the rules for using context.