System Design

G11

Primitives

Go gives you goroutines, channels, select, context, sync and atomics. Each one has exact blocking rules. Here are the rules, recorded from real runs, and the cost of each primitive.

Not startedSaved in this browser only.
  1. 1Every goroutine needs a known way to exit. Before you write go, say what stops it.
  2. 2The goroutine that sends owns the channel, and only the owner closes it.
  3. 3A send or receive on a nil channel blocks forever. In a select, that disables the case.
  4. 4A mutex guards state. A channel moves work or signals an event. An atomic covers one word.
G11
    A

    The trap

    one character, 100 goroutines
    a call with a timeoutgo
    package main
    
    import (
      "fmt"
      "runtime"
      "time"
    )
    
    func fetch(slow <-chan struct{}) string {
      ch := make(chan string)1
      go func() {
        <-slow
        ch <- "ok"2
      }()
      select {
      case v := <-ch:
        return v
      case <-time.After(time.Millisecond)3:
        return "timeout"
      }
    }
    
    func main() {
      slow := make(chan struct{})
      for range 100 {
        fetch(slow)
      }
      close(slow)4
      time.Sleep(100 * time.Millisecond)
      fmt.Println("goroutines:", runtime.NumGoroutine())
    }
    1. 1Unbuffered: a send waits for a receiver.
    2. 2After the timeout no receiver exists. This goroutine stays here until the program ends.
    3. 3The caller leaves through this case and drops ch.
    4. 4Every slow call is now done, and each one tries to send.
    channelrecorded outputstatus
    make(chan string)goroutines: 101100 leaked
    make(chan string, 1)goroutines: 1All exit
    • The buffered send always completes, so the goroutine always exits.
    • The one remaining goroutine is main.
    • The timeout works in both programs. Only the leak differs, so no test on the return value finds it.
    • Each leaked goroutine keeps its stack and everything it references.

    A goroutine that sends after its caller has left blocks forever. I give the send a buffer slot or a way out.

    B

    The model: a goroutine

    measured
    costmeasured
    Memory, parked2,722 B
    Start and finish530 ns
    One unbuffered handoff221 ns
    • The scheduler runs goroutines on GOMAXPROCS threads. A blocked goroutine parks and holds no thread.
    • A stack starts small and grows by copying. The start size follows the average stack use.
    • Memory is the runtime's total growth divided by 100,000 parked goroutines.

    A goroutine costs about 3 KB and about one microsecond. One million parked goroutines use about 3 GB.

    C

    The model: a channel

    runtime/chan.go, Go 1.27
    hchan: make(chan int, 4)lock: guards every fieldbuf (ring)78recvxqcount = 2sendxrecvqgoroutines parked on receivesendqgoroutines parked on sendsendercopies into bufreceivercopies out of bufreceiver waiting:copy straight to ita free slot wakesone parked sender
    • An unbuffered channel is the same struct with no ring. Every send meets a receiver directly.
    • Most operations take the lock and copy a value, so a channel costs more than a mutex (panel Z).
    • Close sets a flag and wakes every parked goroutine in both queues.

    A channel is a locked ring buffer with two queues of parked goroutines. A send to a waiting receiver skips the buffer.

    D

    The rules: send, receive, close

    recorded: each cell is one real operation
    channel statesendreceiveclose
    nilBlocks foreverBlocks foreverPanics close of nil channel
    unbuffered, no partnerBlocks until a receiveBlocks until a sendProceeds
    buffer has roomProceedsBlocks until a sendProceeds
    buffer fullBlocks until a receiveReturns 1, trueProceeds
    closed, value leftPanics send on closed channelReturns 1, truePanics close of closed channel
    closed, drainedPanics send on closed channelReturns 0, falsePanics close of closed channel

    Each receive above uses the form v, ok := <-ch. The buffered channels have capacity 1 and hold the value 1.

    Nil blocks, closed panics on send, and a closed channel gives zero values after its buffer drains. Close panics on nil and on closed.

    E

    The rules: who closes

    ownership
    situationstatus
    One sender closes after its last sendApproved
    Many senders; one goroutine waits for them, then closesApproved
    Close to tell many goroutines to stopUse context
    A receiver closes to stop the senderNot approved
    Each of many senders closes when it endsNot approved
    Close a channel only to free itNot needed

    The garbage collector frees an unreachable channel, closed or not. Close is a signal to receivers.

    The sender closes, because only the sender knows that no more values come. With many senders, a coordinator closes after a WaitGroup.

    F

    The rules: select

    what it does when
    situationresult
    Several cases readyOne at random, so case order is not a priority.
    No case ready, default presentDefault runs at once.
    No case ready, no defaultBlocks until one is ready.
    Case on a nil channelNever ready. Use it to turn a case off.
    Receive on a closed channelAlways ready. A loop spins until you set it to nil.
    select with no casesBlocks forever.

    A timeout is a case on a timer channel. For a priority, check the urgent channel first in a non-blocking select.

    Select picks at random among ready cases. Default makes it non-blocking, and a nil channel removes a case.

    G

    The rules: context

    the context package documentation, and tested below
    rulewhystatus
    Pass ctx as the first parameter of each function on the call pathEach call can stop at the same signal, and readers find it in one place.Approved
    Call cancel on every path, usually with deferThe child stays attached to its parent until cancel runs. go vet reports a lost cancel.Approved
    Select on ctx.Done beside every blocking send and receiveA goroutine that never looks at ctx cannot stop.Approved
    Use WithTimeoutCause or WithCancelCause, and read context.CauseErr only says canceled or deadline exceeded. Cause says why.Approved
    Use WithoutCancel for work that must outlive the requestIt keeps the values and drops the cancel. Add a new timeout to it.Audit logs, cleanup
    Store request-scoped data in values: trace ID, request IDThe data crosses APIs that do not know about it.Request-scoped only
    Put a context in a struct fieldThe struct outlives the call, and the deadline no longer matches the work.Not approved
    Pass optional parameters in valuesThe compiler cannot check them, and the signature hides them.Not approved

    Context goes first because every blocking call on the path needs it. I cancel with a cause, so the log says why the work stopped.

    H

    Mutex or channel

    per situation
    situationusemutexchannel
    Guard a map or a structsync.MutexApprovedSlower, more code
    Keep invariants across several fieldssync.MutexApprovedNot approved
    Hand one unit of work to another goroutinechanNot approvedApproved
    Queue work between stages, with backpressurebuffered chanNot approvedApproved
    Tell many goroutines to stopcontext or closeNot approvedApproved
    Wait with a timeout or with cancellationselectLock cannot time outApproved
    Limit concurrent workbuffered chanNot approvedApproved
    Count one number from many goroutinesatomic.Int64If it joins other fieldsNot approved
    Swap a read-mostly configatomic.PointerIf readers need two fields to agreeNot approved
    Wait for N goroutines to finishsync.WaitGroupNot approvedNot approved

    A mutex protects state. A channel transfers ownership of work or signals an event. I choose by what the goroutines share.

    I

    Which sync type

    numbers measured in the lab, 16 threads
    typeuse it foravoid it when
    MutexMost shared state. Hold it for a few lines.You hold it across I/O. Every other goroutine then waits for the I/O.
    RWMutexReads that hold the lock for a long time: 135 ns against 930 ns with Mutex.Writes dominate: 66.3 ns against 52.7 ns. A reader must not take RLock twice (see the drill).
    OnceOne-time setup with no result.Setup can fail and you want a retry. A panic also counts as done.
    OnceValueLazy values. OnceValues adds an error. OnceFunc has no result.The error is temporary: the first result stays forever.
    WaitGroupWait for a set of goroutines. Go does Add and Done for you.You need the first error or a limit. Use errgroup (see G12).
    CondMany goroutines wait for a state, and the state lives under a mutex.A channel can express it. A Cond wait cannot take a timeout or a context.
    MapKeys that settle early, or goroutines that touch disjoint keys. Reads: 2.8 ns against 40.4 ns.You need a typed API or one value across keys. A map and a mutex are simpler.
    PoolHot, short-lived buffers: 27.5 ns and 0 allocations against 177 ns and 1.You need a cache. The garbage collector empties a pool at any time.

    I start with Mutex. I move to RWMutex only for long reads, and to sync.Map only for keys that settle early.

    J

    A channel with one owner

    tested
    generatego
    // Generate owns out: it makes the channel, sends on it, and closes it.
    func Generate(ctx context.Context, n int) <-chan int1 {
      out := make(chan int)
      go func() {
        defer close(out)2
        for i := range n3 {
          select {
          case out <- i:
          case <-ctx.Done():4
            return
          }
        }
      }()
      return out
    }
    1. 1The return type says the caller can only receive, so the caller cannot close it.
    2. 2Runs on both exits: the last value sent, or ctx ended. A range loop in the caller then ends.
    3. 3Range over an integer: Go 1.22.
    4. 4The way out. Without it, a caller that stops reading leaves this goroutine blocked forever.

    The function that makes the channel starts the sender and closes the channel on every exit path.

    K

    Turn off a select case

    tested
    draingo
    // Drain reads both channels until both close.
    func Drain(a, b <-chan int) []int {
      var got []int
      for a != nil || b != nil1 {
        select {
        case v, ok := <-a:
          if !ok {
            a = nil2
            continue
          }
          got = append(got, v)
        case v, ok := <-b:
          if !ok {
            b = nil
            continue
          }
          got = append(got, v)
        }
      }
      return got
    }
    1. 1The loop ends when both inputs are off.
    2. 2A closed channel is always ready, so the loop would spin. A nil channel is never ready.

    When one input closes, I set its variable to nil. Select then stops looking at it, and the loop ends when both are nil.

    L

    A deadline with a cause

    tested
    callgo
    // ErrSlowBackend says why a call ran out of time.
    var ErrSlowBackend = errors.New("backend too slow")
    
    // Call runs fn with a deadline and returns as soon as ctx ends.
    func Call(
      ctx context.Context, d time.Duration,
      fn func(context.Context) (string, error),
    ) (string, error) {
      ctx, cancel := context.WithTimeoutCause(ctx, d, ErrSlowBackend)1
      defer cancel()2
    
      type result struct {
        v   string
        err error
      }
      done := make(chan result, 1)3
      go func() {
        v, err := fn(ctx)
        done <- result{v, err}
      }()
    
      select {
      case r := <-done:
        return r.v, r.err
      case <-ctx.Done():
        return "", fmt.Errorf("call: %w", context.Cause(ctx)4)
      }
    }
    1. 1The new context ends at d or with its parent, whichever is first. Cause reports ErrSlowBackend for the timeout.
    2. 2Releases the timer and the link to the parent, also on a fast return.
    3. 3One slot: this is the fix from panel A. The send always completes.
    4. 4Returns the parent's cause if the parent ended first, so the caller sees the real reason.

    I derive a deadline with a cause, run the call in a goroutine, and buffer the result so that the goroutine can always exit.

    M

    Context values

    tested
    valuesgo
    type requestIDKey struct{}1
    
    // WithRequestID returns a context that carries id.
    func WithRequestID(ctx context.Context, id string) context.Context {
      return context.WithValue(ctx, requestIDKey{}, id)
    }
    
    // RequestID returns the id in ctx, if there is one.
    func RequestID(ctx context.Context) (string, bool) {
      id, ok := ctx.Value(requestIDKey{}).(string)2
      return id, ok
    }
    1. 1An unexported type: a value of it can only come from this package.
    2. 2Value returns any. The comma-ok form handles a missing key.

    A context key is an unexported type, so no other package can collide with it.

    N

    Run once, keep the result

    tested
    oncevaluesgo
    // Config is a value that is slow to load.
    type Config struct{ Addr string }
    
    // NewLoader returns a function that calls read once and repeats its result.
    func NewLoader(read func() (Config, error)) func() (Config, error) {
      return sync.OnceValues(read)1
    }
    1. 1Concurrent callers wait for the first call. Every later call returns the stored result.

    OnceValues replaces a mutex, a flag and two fields. It runs once and repeats the result.

    O

    WaitGroup.Go

    tested
    parallelmapgo
    // ParallelMap applies f to each element in its own goroutine.
    func ParallelMap[T, R any](in []T, f func(T) R) []R {
      out := make([]R, len(in))2
      var wg sync.WaitGroup
      for i, v := range in {
        wg.Go(func() { out[i] = f(v) })1
      }
      wg.Wait()3
      return out
    }
    1. 1Go 1.25. Each iteration has its own i and v since Go 1.22, so the closure needs no arguments.
    2. 2Allocate before the goroutines start. Each goroutine writes one element, and elements are separate memory.
    3. 3The return from f synchronizes with this Wait, so reading out afterwards is safe.

    This starts one goroutine per element. For a long list, set a limit (see G12).

    WaitGroup.Go does the Add and the Done, so the classic misplaced Add cannot happen. Writing to separate slice elements needs no lock.

    P

    RWMutex

    tested
    rwmutexgo
    // Table is a map that many goroutines read and few write.
    type Table struct {
      mu   sync.RWMutex
      rows map[string]string
    }
    
    // NewTable returns an empty table.
    func NewTable() *Table { return &Table{rows: make(map[string]string)} }
    
    // Get returns the row for key.
    func (t *Table) Get(key string) (string, bool) {
      t.mu.RLock()1
      defer t.mu.RUnlock()
      v, ok := t.rows[key]
      return v, ok
    }
    
    // Set stores the row for key.
    func (t *Table) Set(key, value string) {
      t.mu.Lock()2
      defer t.mu.Unlock()
      t.rows[key] = value
    }
    1. 1Readers share the lock. A waiting writer blocks new readers.
    2. 2One writer, with no readers.

    RWMutex lets readers run together. It gains most on long reads and loses when writes dominate, so I measure first.

    Q

    Cond: wait for a state

    tested
    condgo
    // Queue is a bounded FIFO. Get and Put wait instead of failing.
    type Queue[T any] struct {
      mu       sync.Mutex
      nonEmpty *sync.Cond
      nonFull  *sync.Cond
      items    []T
      limit    int
      closed   bool
    }
    
    // NewQueue returns a queue that holds at most limit items.
    func NewQueue[T any](limit int) *Queue[T] {
      q := &Queue[T]{limit: limit}
      q.nonEmpty = sync.NewCond(&q.mu)
      q.nonFull = sync.NewCond(&q.mu)
      return q
    }
    
    // Put waits for room, then adds v. It reports false after Close.
    func (q *Queue[T]) Put(v T) bool {
      q.mu.Lock()
      defer q.mu.Unlock()
      for len(q.items) == q.limit && !q.closed1 {
        q.nonFull.Wait()2
      }
      if q.closed {
        return false
      }
      q.items = append(q.items, v)
      q.nonEmpty.Signal()3
      return true
    }
    
    // Get waits for an item. It reports false when the queue is closed and empty.
    func (q *Queue[T]) Get() (T, bool) {
      q.mu.Lock()
      defer q.mu.Unlock()
      for len(q.items) == 0 && !q.closed {
        q.nonEmpty.Wait()
      }
      var v T
      if len(q.items) == 0 {
        return v, false
      }
      v, q.items = q.items[0], q.items[1:]
      q.nonFull.Signal()
      return v, true
    }
    
    // Close wakes every waiter.
    func (q *Queue[T]) Close() {
      q.mu.Lock()
      defer q.mu.Unlock()
      q.closed = true
      q.nonEmpty.Broadcast()4
      q.nonFull.Broadcast()
    }
    1. 1Always a loop: another goroutine can take the slot before this one runs.
    2. 2Releases the mutex while it waits, and takes it again before it returns.
    3. 3One new item wakes one reader.
    4. 4Close changes the state for every waiter, so wake all of them.

    Cond waits in a loop on a state under the mutex. Signal wakes one goroutine, and Broadcast wakes all of them.

    R

    sync.Map

    tested
    syncmapgo
    // Counters is a set of named counters. The names settle early.
    type Counters struct{ m sync.Map }
    
    // Inc adds one to the named counter.
    func (c *Counters) Inc(name string) {
      v, ok := c.m.Load(name)1
      if !ok {
        v, _ = c.m.LoadOrStore(name, new(atomic.Int64))2
      }
      v.(*atomic.Int64).Add(1)
    }
    
    // Get returns the named counter.
    func (c *Counters) Get(name string) int64 {
      v, ok := c.m.Load(name)
      if !ok {
        return 0
      }
      return v.(*atomic.Int64).Load()
    }
    1. 1The common path: no allocation.
    2. 2Two goroutines can race here. Both get the one stored counter.

    sync.Map suits keys that settle early. The value type is any, so I wrap it in a small typed struct.

    S

    sync.Pool

    tested
    poolgo
    var buffers = sync.Pool{New: func() any { return new(bytes.Buffer) }}
    
    // Greeting builds a string in a reused buffer.
    func Greeting(name string) string {
      b := buffers.Get().(*bytes.Buffer)
      b.Reset()1
      defer buffers.Put(b)2
      b.WriteString("hello, ")
      b.WriteString(name)
      return b.String()3
    }
    1. 1A pooled object keeps its old contents. Reset it before use.
    2. 2After Put, another goroutine can have the buffer. Do not keep a reference.
    3. 3String copies the bytes, so the result survives the Put.

    A pool reuses buffers on a hot path. I reset on Get, I never keep a pointer after Put, and I expect it to be empty at any time.

    T

    Atomic types

    tested
    atomicgo
    // Limits is an immutable value: replace it, never change it.
    type Limits struct{ MaxBytes int }
    
    // Gate reads its limits on every request and takes no lock.
    type Gate struct {
      limits atomic.Pointer[Limits]1
      served atomic.Int642
    }
    
    // NewGate returns a gate with the first limits.
    func NewGate(l Limits) *Gate {
      g := &Gate{}
      g.limits.Store(&l)3
      return g
    }
    
    // Allow admits a request of the given size and counts it.
    func (g *Gate) Allow(size int) bool {
      if size > g.limits.Load().MaxBytes {
        return false
      }
      g.served.Add(1)
      return true
    }
    
    // Update replaces the limits for every later Allow.
    func (g *Gate) Update(l Limits) { g.limits.Store(&l) }
    
    // Served returns how many requests passed.
    func (g *Gate) Served() int64 { return g.served.Load() }
    1. 1Typed since Go 1.19: no unsafe.Pointer, and no plain read of the value can compile.
    2. 2Always aligned to 64 bits, also on 32-bit systems.
    3. 3Copy on write. Each Limits value stays immutable after Store.

    Go atomics are sequentially consistent. There are no relaxed forms to choose from.

    Readers load a pointer to an immutable value with no lock. A writer builds a new value and swaps the pointer.

    U

    Test it with a fake clock

    tested
    test for a leakgo
    func TestCallDoesNotLeakOnTimeout(t *testing.T) {
      synctest.Test1(t, func(t *testing.T) {
        release := make(chan struct{})
        slow := func(context.Context) (string, error) {
          <-release
          return "late", nil
        }
        _, err := Call(t.Context(), time.Millisecond, slow)
        if !errors.Is(err, ErrSlowBackend) {
          t.Fatalf("err = %v", err)
        }
        close(release)
        // A bubble fails when a goroutine is blocked at its end.
        synctest.Wait()2
      })
    }
    1. 1Starts a bubble. Time jumps forward when every goroutine in the bubble blocks.
    2. 2Waits until every other goroutine in the bubble has blocked or exited.

    A mutex wait is not durable in a bubble, because a goroutine outside could release the mutex. Run these tests with -race too.

    I test timeouts inside a synctest bubble. Time is fake, so the test is instant and exact, and a stuck goroutine fails it.

    V

    See it: one handoff, step by step

    recorded on a fake clock
    make(chan int, n), n =
    0102030405060708090100110120130producer1222333444bufferconsumer111222333444

    t = 0 ms

    The producer computes item 1.

    The consumer blocks: the channel is empty.

    Finished at 130 ms. The producer spent 60 ms blocked.
    • works
    • blocked on send
    • blocked on receive
    • finished
    • The producer needs 10 ms per item and the consumer needs 30 ms. Each cell is 10 ms.
    • Capacity changes who waits, and when. The finish time does not change.
    • Use a buffer for bursts, or for a known number of sends. Do not use one to hide a slow consumer.

    A buffer moves the wait. It does not make a slow consumer faster: the run takes the same time at every capacity.

    W

    New in recent Go

    checked against each release's notes
    sincewhat changedwhat it means here
    1.19Typed atomics: atomic.Int64, atomic.Pointer[T]. The memory model is revised. Start stack size follows the average use.Prefer these types to the function forms.
    1.20context.WithCancelCause and context.Cause. sync.Map gets Swap, CompareAndSwap and CompareAndDelete.Cancel with a reason.
    1.21sync.OnceFunc, OnceValue, OnceValues. context.WithoutCancel, WithDeadlineCause, WithTimeoutCause, AfterFunc.Most hand-written lazy init can go.
    1.22Each loop iteration creates new variables. Range over an integer.The copy i := i before go is no longer needed.
    1.23Timer channels are unbuffered, and unreferenced timers are collected without Stop. sync.Map.Clear. atomic And and Or.No stale value after Reset or Stop. len on a timer channel is 0.
    1.24New sync.Map implementation. testing.B.Loop. T.Context and B.Context.Writes to disjoint keys contend less.
    1.25sync.WaitGroup.Go. testing/synctest. GOMAXPROCS follows the cgroup CPU limit on Linux and updates at run time. go vet reports a misplaced WaitGroup.Add. runtime/trace.FlightRecorder.Container limits apply with no extra library.
    1.26signal.NotifyContext cancels with a cause that names the signal. The Green Tea collector is the default. goroutineleak profile as an experiment.context.Cause tells you which signal stopped the server.
    1.27goroutineleak profile is generally available in runtime/pprof and at /debug/pprof/goroutineleak. synctest.Sleep. The asynctimerchan setting is gone, so timer channels are always unbuffered.Find the leak from panel A in production. See G12 for a test.
    X

    In the round

    45 minutes of build, 45 minutes of talk
    whenthe momentwhat to do or say
    buildThe store has a map and concurrent requests.Add a mutex to the store struct on the first line. Say why: net/http runs each request in its own goroutine.
    buildA background sweep removes expired entries.Use a ticker in a goroutine, with a select on ctx.Done. Keep the lock for the sweep short.
    buildA test must prove the store is safe.Start N goroutines with wg.Go, assert the invariant, run go test -race.
    buildA handler calls something slow.Pass r.Context() down. It ends when the client disconnects.
    talk"Why a mutex, not a channel?"The goroutines share state, and they do not pass work. A channel here adds a goroutine and costs more per operation.
    talk"What stops this goroutine?"Name the signal: ctx.Done, or a closed input channel. Then name the test that proves it.
    talk"How do you find a leak in production?"Watch the goroutine count, then read the goroutineleak profile. It reports blocked goroutines that nothing can reach.
    talk"What does RWMutex buy you?"Read the numbers in panel I. Its value depends on the hold time and the write share, so measure first.

    I run my tests with -race, and for each goroutine I can say what stops it.

    Y

    Drill

    each answer is the output of a real run

    0 of 12 known

    1. Predict the output. The channel is closed before the first receive.

      package main
      
      import "fmt"
      
      func main() {
        ch := make(chan int, 3)
        ch <- 1
        ch <- 2
        close(ch)
        fmt.Println(len(ch), cap(ch))
        for range 3 {
          v, ok := <-ch
          fmt.Println(v, ok)
        }
      }
    2. Predict the output.

      package main
      
      import "fmt"
      
      func main() {
        var ch chan int
        fmt.Println(len(ch), cap(ch))
        ch <- 1
        fmt.Println("sent")
      }
    3. Predict the output. The buffer has room.

      package main
      
      import "fmt"
      
      func main() {
        ch := make(chan int, 1)
        close(ch)
        defer func() {
          fmt.Println("recovered:", recover())
          v, ok := <-ch
          fmt.Println(v, ok)
        }()
        ch <- 1
        fmt.Println("sent")
      }
    4. Predict the output.

      package main
      
      import "fmt"
      
      func main() {
        ch := make(chan int)
        select {
        case ch <- 1:
          fmt.Println("sent")
        default:
          fmt.Println("no receiver")
        }
      
        buf := make(chan int, 1)
        select {
        case buf <- 1:
          fmt.Println("sent")
        default:
          fmt.Println("no room")
        }
      }
    5. Predict the output. Both channels hold a value.

      package main
      
      import "fmt"
      
      func main() {
        a := make(chan string, 1)
        b := make(chan string, 1)
        a <- "a"
        b <- "b"
        select {
        case v := <-a:
          fmt.Println(v)
        case v := <-b:
          fmt.Println(v)
        }
      }
    6. Predict the output.

      package main
      
      import "fmt"
      
      func main() {
        done := make(chan struct{})
        close(done)
        var never chan int
        count := 0
        for range 1000 {
          select {
          case <-never:
            fmt.Println("never")
          case <-done:
            count++
          }
        }
        fmt.Println(count)
      }
    7. Predict the output.

      package main
      
      import (
        "context"
        "fmt"
      )
      
      func main() {
        parent, cancelParent := context.WithCancel(context.Background())
        child, cancelChild := context.WithCancel(parent)
        detached := context.WithoutCancel(parent)
      
        cancelChild()
        fmt.Println(parent.Err(), child.Err())
      
        cancelParent()
        fmt.Println(parent.Err(), child.Err(), detached.Err())
      }
    8. Predict the output.

      package main
      
      import (
        "context"
        "errors"
        "fmt"
      )
      
      func main() {
        ctx, cancel := context.WithCancelCause(context.Background())
        cancel(errors.New("disk full"))
        cancel(errors.New("second call"))
        fmt.Println(ctx.Err())
        fmt.Println(context.Cause(ctx))
      }
    9. Predict the output. The counter shows how often the function ran.

      package main
      
      import (
        "fmt"
        "sync"
      )
      
      func main() {
        calls := 0
        boom := func() int {
          calls++
          panic("boom")
        }
        v := sync.OnceValue(boom)
        var once sync.Once
        do := func() { once.Do(func() { boom() }) }
      
        for range 2 {
          func() {
            defer func() { fmt.Println("OnceValue:", recover(), calls) }()
            v()
          }()
        }
        calls = 0
        for range 2 {
          func() {
            defer func() { fmt.Println("Once:", recover(), calls) }()
            do()
          }()
        }
      }
    10. Predict the output. The timer fires long before the first print.

      package main
      
      import (
        "fmt"
        "time"
      )
      
      func main() {
        t := time.NewTimer(time.Millisecond)
        time.Sleep(20 * time.Millisecond)
        fmt.Println(len(t.C), cap(t.C))
      
        t.Reset(time.Hour)
        select {
        case <-t.C:
          fmt.Println("stale tick")
        default:
          fmt.Println("no tick")
        }
      }
    11. Predict the output. The goroutine waits for the write lock while main holds a read lock.

      package main
      
      import (
        "fmt"
        "sync"
        "time"
      )
      
      func main() {
        var mu sync.RWMutex
        mu.RLock()
        go func() {
          mu.Lock()
          mu.Unlock()
        }()
        time.Sleep(10 * time.Millisecond)
        mu.RLock()
        fmt.Println("second read lock taken")
      }
    12. Predict the output.

      package main
      
      import (
        "fmt"
        "sync"
      )
      
      func main() {
        defer func() {
          fmt.Println("recovered:", recover())
        }()
        var mu sync.Mutex
        mu.Unlock()
      }
    Z

    Numbers to say

    measured with testing.B
    atomic add
    5.7 ns; 14.5 ns under contention.
    mutex
    12.6 ns alone; 52.8 ns contended.
    channel
    51.1 ns buffered; 221 ns unbuffered.
    goroutine
    530 ns to start and finish; about 2.7 KB parked.
    Once
    1.3 ns after the first call.
    ratio
    An unbuffered handoff costs about 4 times a contended mutex.

    Go 1.27.3, 8-core Intel i9 laptop, GOMAXPROCS 16, median of 3 runs of 1 s, on a busy machine. Use these as orders of magnitude.