System Design

G9

The memory model

The memory model says which writes a read can see. Each synchronizing operation creates an edge between goroutines. Without an edge, the compiler and the CPU owe you nothing, and these programs show it.

Not startedSaved in this browser only.
  1. 1A read sees a write only if an edge orders them. Time on a clock does not order anything.
  2. 2Two accesses race if one is a write, they have no order, and they are not all atomic.
  3. 3A racy program can see values that no goroutine wrote. It does not fail safely.
  4. 4The race detector finds races on code that ran. A clean run proves only that run.
G9
    A

    The trap

    recorded on 20 runs
    a stop flaggo
    // The flag is a plain bool. A goroutine sets it after 100 ms.
    package main
    
    import (
      "fmt"
      "os"
      "time"
    )
    
    var done bool
    
    func wait() {
      if done {1
        return
      }
      for !done {2
      }
    }
    
    func main() {
      go func() {
        time.Sleep(100 * time.Millisecond)
        done = true3
      }()
      time.AfterFunc(time.Second, func() {
        fmt.Println("1 s later: done =", done, "and main still spins")
        os.Exit(1)
      })
      wait()
      fmt.Println("main saw done")
    }
    1. 1The first read of done.
    2. 2No goroutine may change done between these reads without an edge. So the compiler keeps the first value and spins on it.
    3. 3This write happens. The print proves it. The loop never reads memory again.
    flagrecorded outputstatus
    bool1 s later: done = true and main still spinsNever ends, exit 1 from the timer
    atomic.Boolmain saw doneEnds
    • The timer goroutine reads done as true. Main reads it as false, 900 ms after the write.
    • This is a compiler result, on one CPU type and one Go version. The model allows it on all of them.
    • The only change between the two programs is the type of the flag.

    A plain flag is not a signal. With no edge, the compiler can reuse the first read forever. I use an atomic or a channel.

    B

    The model: happens-before

    partial order, not time
    goroutine Agoroutine Ba = 1c <- 0b = 2<-cprint(a, b)edgeno order on b
    • Inside one goroutine, each step comes before the next.
    • A synchronizing operation adds an edge from one goroutine to another.
    • Follow the arrows. If a path joins two steps, they have an order.
    • If no path joins them, they are concurrent, whatever the wall clock says.

    Happens-before is a partial order. Inside a goroutine it follows the code. Across goroutines, only synchronizing operations add edges.

    C

    What counts as a data race

    each verdict from the race detector
    two goroutinesverdict
    Two goroutines write one int. Two writes with no order.Race reported
    One writes, one reads. One write is enough.Race reported
    Two goroutines read. A race needs a write.No race
    Each writes its own slice element. Elements are separate memory locations.No race
    Each writes its own struct field. Fields are separate memory locations.No race
    Both use atomics. Atomic accesses cannot race.No race
    One atomic write, one plain write. All accesses must be atomic.Race reported
    Both hold one mutex. Unlock orders the critical sections.No race
    Each holds a different mutex. Two mutexes give no order between them.Race reported
    One writes a map, one reads another key. A map is one data structure, not one location per key.Race reported

    A data race is a write and another access to one location, with no order, unless all of them are atomic.

    D

    See it: a happens-before graph

    replayed with vector clocks, then confirmed by the race detector
    package main
     
    import (
      "fmt"
      "time"
    )
     
    var a string
     
    func main() {
      go func() {
        a = "hello"
      }()
      time.Sleep(10 * time.Millisecond)
      fmt.Println(a)
    }
    
    mainworkergo func()a = "hello"time.Sleepread a

    step 1 of 4, clock [1, 0]

    Inside one goroutine, each step comes after the previous step.

    0 of 0 earlier steps happen before this one.

    • selected step
    • happens before it
    • no order with it
    • synchronizing edge
    • data race
    • Each program shows one schedule that really runs. Click a step, or step through it.
    • A test runs each real program under the race detector and compares the verdict with this graph.
    • Compare the unbuffered and buffered programs. The code differs by one number, and only one is correct.

    I follow the arrows from the write to the read. If no path exists, the code has a race, even if it always prints the right value.

    E

    The rules: what creates an edge

    the Go memory model and the sync package documentation
    operationthe edgestatus
    go f()The go statement comes before the first step of f.Edge
    goroutine exitNo edge to anything. Use a WaitGroup or a channel.No edge
    ch <- vA send comes before the completion of its receive.Edge
    close(ch)A close comes before a receive that returns a zero value because of it.Edge
    <-ch, unbufferedA receive comes before the matching send returns.Edge
    <-ch, capacity CReceive number k comes before send number k+C returns. A semaphore uses this rule.Not the first C sends
    mu.Unlock()Unlock number n comes before Lock number n+1 returns.Edge
    RWMutexThe same for Lock. RLock returns after the earlier Unlock, and RUnlock comes before the next Lock.Edge
    mu.TryLock()A failed TryLock creates no edge.Only when it succeeds
    once.Do(f)The return of f comes before the return of every Do.Edge
    sync/atomicA store comes before a load that observes it. All atomics have one total order.Only if the load sees it
    wg.Done()Done comes before the return of the Wait that it unblocks.Edge
    cond.Signal()Signal comes before the Wait that it wakes returns.Edge
    sync.MapA write comes before a read that observes it.Only if the read sees it
    pool.Put(x)Put comes before the Get that returns x.Only that x
    time.SleepNo edge. It changes the timing and nothing else.No edge

    Tests pass a plain string through the go statement, channels, Mutex, Once, atomics, WaitGroup, Cond and sync.Map under -race. The other rows come from the documentation. See G11 for how each type works.

    I can name the edge for each shared variable: which unlock, which send, which atomic store. If I cannot name it, I have a race.

    F

    Edges from go, send and close

    tested under -race
    start and channel edgesgo
    // ViaGo: the go statement comes before the first step of the goroutine.
    func ViaGo() string {
      msg := "hello"1
      out := make(chan string, 1)
      go func() { out <- msg }()
      return <-out
    }
    
    // ViaSend: a send comes before the completion of its receive.
    func ViaSend() string {
      var msg string
      c := make(chan struct{}, 1)
      go func() {
        msg = "hello"
        c <- struct{}{}2
      }()
      <-c
      return msg
    }
    
    // ViaClose: a close comes before a receive that returns because of it.
    func ViaClose() string {
      var msg string
      done := make(chan struct{})
      go func() {
        msg = "hello"
        close(done)3
      }()
      <-done
      return msg
    }
    1. 1This write comes before the go statement, so the goroutine sees it.
    2. 2The write to msg is above this line. The receive completes after it.
    3. 3A close wakes every receiver, so one close publishes to many goroutines.

    Each plain value crosses the goroutine boundary on an edge, so no lock is needed for that one handoff.

    G

    Edges from lock, once and atomics

    tested under -race
    lock, once and atomic edgesgo
    // ViaMutex: the nth Unlock comes before the n+1th Lock returns.
    func ViaMutex() string {
      var mu sync.Mutex
      var msg string
      wrote := make(chan struct{})
      go func() {
        mu.Lock()
        defer mu.Unlock()
        msg = "hello"
        close(wrote)1
      }()
      <-wrote
      mu.Lock()
      defer mu.Unlock()
      return msg
    }
    
    // ViaOnce: the one run of f comes before every Do returns.
    func ViaOnce() [2]string {
      var once sync.Once
      var msg string
      var got [2]string
      var wg sync.WaitGroup
      for i := range got {
        wg.Go(func() {
          once.Do(func() { msg = "hello" })2
          got[i] = msg
        })
      }
      wg.Wait()
      return got
    }
    
    // ViaAtomic: a store comes before the load that observes it.
    func ViaAtomic() string {
      var msg string
      var ready atomic.Bool
      go func() {
        msg = "hello"
        ready.Store(true)3
      }()
      for !ready.Load() {4
      }
      return msg
    }
    1. 1This channel only makes the goroutine run first. The mutex alone gives the order, not the first turn.
    2. 2Every caller gets the edge, also a caller that did not run f.
    3. 3A plain write above this store becomes visible to the load that sees true.
    4. 4A spin works but burns a CPU. A channel parks the goroutine. This loop only shows the edge.

    An atomic orders what came before the store, not only the atomic value. That is why a flag can publish a whole struct.

    H

    Why a racy program has no meaning

    this varies: values from real runs
    race onsizewhat the model allowsrecorded in 5 runsstatus
    A plain counter1 wordEach read sees some real write, so increments are lost. 8 goroutines add 100,000 each.207179, 218009, 218093, 227076, 237944Wrong total
    An interface value2 wordsThe type word of one write with the data word of another.torn read: cat method, name dog; torn read: dog method, name catWrong method for the data
    A slice value3 wordsThe pointer of one write with the length of another.slice of 1 byte, len 1048576: index 4096 passes the bounds checkBounds check defeated
    a torn interfacego
    // An interface value is two words: a type and a pointer to data. One
    // goroutine swaps it with no lock, and main calls a method on what it reads.
    package main
    
    import (
      "fmt"
      "sync/atomic"
    )
    
    type speaker interface{ say() string }
    
    type cat struct{ name string }
    type dog struct{ name string }
    
    func (c *cat) say() string { return "cat method, name " + c.name }
    func (d *dog) say() string { return "dog method, name " + d.name }
    
    var (
      shared speaker
      writes atomic.Int64
    )
    
    func main() {
      c, d := &cat{"cat"}, &dog{"dog"}
      shared = c
      go func() {
        for {
          if writes.Add(1)%2 == 01 {
            shared = c
          } else {
            shared = d
          }
        }
      }()
      for range 500_000_000 {
        s := shared.say()2
        if s != "cat method, name cat" && s != "dog method, name dog" {
          fmt.Println("torn read:", s)
          return
        }
      }
      fmt.Println("no torn value in 500,000,000 reads")
    }
    1. 1The atomic add is a fence on this CPU, so each store leaves the store buffer. Without it, these runs showed no tear.
    2. 2Two loads: the type word, then the data word. The writer can run between them.
    a torn slicego
    // A slice value is three words. The reader can take the pointer of one
    // slice and the length of another, and the bounds check uses that length.
    package main
    
    import (
      "fmt"
      "sync/atomic"
    )
    
    var (
      shared []byte
      writes atomic.Int64
    )
    
    func main() {
      short := make([]byte, 1)
      long := make([]byte, 1<<20)
      shared = short
      go func() {
        for {
          if writes.Add(1)%2 == 0 {
            shared = short
          } else {
            shared = long
          }
        }
      }()
      for range 500_000_000 {
        s := shared
        if len(s) == len(long) && &s[0] == &short[0]1 {
          fmt.Printf("slice of 1 byte, len %d: index 4096 passes the2 "+
            "bounds check\n", len(s))
          return
        }
      }
      fmt.Println("no torn value in 500,000,000 reads")
    }
    1. 1The pointer is from the 1-byte slice, and the length is from the long slice.
    2. 2The bounds check trusts the length, so the program can read and write outside the array.

    Here the two types have one layout, so the tear only gives a wrong answer. With different layouts, a method reads the data as the wrong type. Strings and maps have the same risk.

    A word-sized race reads an old or a new value. A multiword race can read a mix, and then memory safety is gone.

    I

    Double-checked locking

    the race is real, and the bug did not show here
    the broken formgo
    // Double-checked locking with a plain flag. The first check takes no lock.
    package main
    
    import (
      "fmt"
      "sync"
    )
    
    type config struct{ port int }
    
    var (
      mu    sync.Mutex
      ready bool
      cfg   *config
    )
    
    func get() *config {
      if ready { // first check: no lock
        return cfg
      }
      mu.Lock()
      defer mu.Unlock()
      if !ready {
        cfg = &config{port: 8080}
        ready = true2
      }
      return cfg
    }
    
    func main() {
      var wg sync.WaitGroup
      wrong := 0
      var count sync.Mutex
      for range 64 {
        wg.Go(func() {
          if c := get(); c == nil || c.port != 8080 {
            count.Lock()
            defer count.Unlock()
            wrong++
          }
        })
      }
      wg.Wait()
      fmt.Println("wrong reads:", wrong)
    }
    1. 1No edge joins this read to the write under the lock.
    2. 2The memory model lets another goroutine see this store before it sees cfg.
    -race, first reportexit 66
    ==================
    WARNING: DATA RACE
    Write at 0x000010ac6e08 by goroutine 8:
      main.get()
          main.go:25 +0x10d
      main.main.func1()
          main.go:36 +0x32
    
    Previous read at 0x000010ac6e08 by goroutine 7:
      main.get()
          main.go:18 +0x30
      main.main.func1()
          main.go:36 +0x32
    
    Goroutine 8 (running) created at:
      sync.(*WaitGroup).Go()
          $GOROOT/src/sync/waitgroup.go:238 +0x72
    
    Goroutine 7 (running) created at:
      sync.(*WaitGroup).Go()
          $GOROOT/src/sync/waitgroup.go:238 +0x72
    ==================
    • Without -race, the program printed "wrong reads: 0" on this CPU. The CPU keeps stores in order, so this bug needs a compiler or a weaker CPU.
    • Arm64 keeps fewer orders. Do not rely on a test on a laptop.
    • The detector reports the race although the output is right, because it checks the order, not the result.

    The fast path of a hand-written double check reads a plain flag. Seeing the flag does not prove that I see the data.

    J

    The correct form

    tested
    double check that worksgo
    // Lazy builds a value on first use. The fast path is one atomic load, and
    // that load is what makes the first check safe: a reader that sees the
    // pointer also sees everything the builder wrote before it stored the
    // pointer. Prefer sync.OnceValue. Use this form only when a failed build
    // must retry.
    type Lazy[T any] struct {
      value atomic.Pointer[T]1
      mu    sync.Mutex
      build func() (T, error)
    }
    
    // NewLazy returns a Lazy that calls build until one call succeeds.
    func NewLazy[T any](build func() (T, error)) *Lazy[T] {
      return &Lazy[T]{build: build}
    }
    
    // Get returns the value, and builds it if no build has succeeded yet.
    func (l *Lazy[T]) Get() (*T, error) {
      if v := l.value.Load(); v != nil {
        return v, nil
      }
      l.mu.Lock()3
      defer l.mu.Unlock()
      if v := l.value.Load(); v != nil {
        return v, nil
      }
      v, err := l.build()
      if err != nil {
        return nil, err
      }
      l.value.Store(&v)2
      return &v, nil
    }
    1. 1The first check is now an atomic load, so it can observe the store.
    2. 2Everything build wrote comes before this store. A load that sees the pointer sees all of it.
    3. 3The mutex makes one builder at a time. The atomic carries the edge to readers.

    I use sync.OnceValue. If a failed build must retry, I keep a double check with an atomic pointer for the first read.

    K

    The rules: what to do

    for any shared variable
    practicestatus
    One goroutine owns the dataApproved
    One mutex guards each fieldApproved
    Build, then publish, then never writeApproved
    A plain bool as a stop flagNot approved
    A sleep to wait for a goroutineNot approved
    "This word is small, so it is safe"Not approved
    Publish with an atomic, then writeNot approved

    I name the rule for each shared variable: owned by one goroutine, guarded by this mutex, or immutable after publish.

    L

    What -race finds, and what it cannot

    recorded where a row shows a run
    situationresultstatus
    Two accesses ran with no edgeReport with both stacks, and exit code 66 when the program endsFound
    Correct output, wrong order (panel I)Reported. It checks the order, not the outputFound
    The racy path did not run (panel N)Exit 0, output "hits: 0". With the path taken: exit 66Missed
    This schedule added an edge by luck (panel M)Exit 0 on one schedule, exit 66 on the otherOnly on some schedules
    Every access is locked, but the logic is wrongNo race exists to report. See G13Missed
    Deadlocks and leaked goroutinesNot a data race. See G13Missed
    Old historyThe race report can say "failed to restore the stack". Raise GORACE history_sizeReport loses a stack

    Halt on the first race with GORACE="halt_on_error=1". By default, the program prints each report and runs on. Cost: see panel R.

    The race detector reports only what it saw, and it sees only what ran. So I run it under real load as well as in tests.

    M

    One program, two schedules

    recorded
    the race depends on who runs firstgo
    // One program, two schedules. The mutex guards nothing here, but it can
    // add an edge between the write and the read if the writer unlocks first.
    package main
    
    import (
      "fmt"
      "os"
      "sync"
      "time"
    )
    
    var (
      mu sync.Mutex
      x  int
    )
    
    func writer() {
      x = 11
      mu.Lock()
      defer mu.Unlock()3
    }
    
    func reader() int {
      mu.Lock()
      mu.Unlock()
      return x2
    }
    
    func main() {
      writerDelay, readerDelay := time.Duration(0), 20*time.Millisecond
      if os.Args[1] == "reader-first" {
        writerDelay, readerDelay = readerDelay, writerDelay
      }
      var wg sync.WaitGroup
      wg.Go(func() {
        time.Sleep(writerDelay)
        writer()
      })
      wg.Go(func() {
        time.Sleep(readerDelay)
        fmt.Println("read", reader())
      })
      wg.Wait()
    }
    1. 1Outside the mutex. This access has no guard.
    2. 2Also outside the mutex.
    3. 3If the writer unlocks first, the reader's Lock takes an edge from this Unlock. That edge orders the two accesses.
    scheduleprintedexit
    Writer firstread 10
    Reader firstread 066
    reader first: the reportrecorded
    ==================
    WARNING: DATA RACE
    Write at1 0x000005ab5ea8 by goroutine 7:
      main.writer()
          main.go:18 +0x27
      main.main.func1()
          main.go:38 +0x33
    
    Previous read at2 0x000005ab5ea8 by goroutine 8:
      main.reader()
          main.go:27 +0x3c
      main.main.func2()
          main.go:42 +0x33
    
    Goroutine 7 (running) created at:3
      sync.(*WaitGroup).Go()
          $GOROOT/src/sync/waitgroup.go:238 +0x72
    
    Goroutine 8 (finished) created at:
      sync.(*WaitGroup).Go()
          $GOROOT/src/sync/waitgroup.go:238 +0x72
    ==================
    1. 1The access that the detector caught last.
    2. 2The earlier access in its history. Fix the pair, not one line.
    3. 3Where the goroutine began. The goroutine number differs on each run.

    A mutex that guards nothing can still hide a race on a good schedule, because the detector sees the edge that this run made.

    N

    A path that did not run

    recorded
    the racy path needs an argumentgo
    // A race on a path that runs only with an argument.
    package main
    
    import (
      "fmt"
      "os"
      "sync"
    )
    
    func main() {
      hits := 0
      var wg sync.WaitGroup
      wg.Go(func() {
        if len(os.Args) > 1 {
          hits++1
        }
      })
      wg.Go(func() {
        if len(os.Args) > 1 {
          hits++
        }
      })
      wg.Wait()
      fmt.Println("hits:", hits)
    }
    1. 1A real race, on a path that needs an input the test did not give.
    runprintedexitstatus
    No argumenthits: 00Clean, and the race is still there
    One argumentFound 1 data race(s)66Found

    The detector sees executed code only, so race coverage equals test coverage. I add concurrent tests for each shared path.

    O

    New in recent Go

    checked against each release's notes
    sincewhat changedwhat it means here
    1.19The memory model was revised to match C, C++, Java, JavaScript, Rust and Swift. Go has sequentially consistent atomics only. New types: atomic.Int64, atomic.Pointer[T] and others.No relaxed forms to choose from. A typed atomic cannot be read by accident with a plain load.
    1.21sync.OnceFunc, OnceValue and OnceValues.Replaces most hand-written double checks.
    1.22Each iteration of a for loop creates new variables.A closure no longer shares the loop variable. Vet stops the old report for files at 1.22 or later.
    1.25sync.WaitGroup.Go. Vet reports a misplaced WaitGroup.Add. The race detector supports linux/loong64.The late Add from the drill cannot happen with wg.Go.
    1.26The race detector supports linux/riscv64.One more server target can run -race.

    Go 1.27 has no memory model change and no race detector change in its release notes.

    P

    In the round

    45 minutes of build, 45 minutes of talk
    whenthe momentwhat to do or say
    buildA handler reads a map that another handler writes.Guard it now. A read counts: one write plus any read is a race.
    buildA background goroutine must stop.Use ctx.Done, not a plain bool. Panel A shows why.
    buildYou add a concurrency test.Run with -race, and make goroutines overlap on real work. The detector only sees what ran.
    talk"Is reading an int without a lock safe?"No. The result is some real value, but the compiler can reuse it forever, and the program has a race.
    talk"Why not double-checked locking?"Seeing the flag does not order the data. Use sync.OnceValue, or an atomic pointer.
    talk"What does -race miss?"Paths that did not run, logic races under correct locks, deadlocks and leaks.
    talk"Do you run -race in production?"In a canary, at most. It costs about 7.5 times the time and 4.0 times the memory here.

    I never argue from timing. I name the edge, and I run the tests with -race.

    Q

    Drill

    each answer is the output of a real run

    0 of 10 known

    1. Predict the output.

      package main
      
      import "fmt"
      
      var a string
      
      func main() {
        c := make(chan int, 10)
        go func() {
          a = "hello"
          c <- 0
        }()
        <-c
        fmt.Printf("%q\n", a)
      }
    2. Predict the output.

      package main
      
      import "fmt"
      
      var a string
      
      func main() {
        c := make(chan int, 10)
        go func() {
          a = "hello"
          close(c)
        }()
        v, ok := <-c
        fmt.Printf("%d %v %q\n", v, ok, a)
      }
    3. Predict the output. The receive is in the goroutine.

      package main
      
      import "fmt"
      
      var a string
      
      func main() {
        c := make(chan int)
        go func() {
          a = "hello"
          <-c
        }()
        c <- 0
        fmt.Printf("%q\n", a)
      }
    4. Predict the output. The goroutine unlocks a mutex that main locked.

      package main
      
      import (
        "fmt"
        "sync"
      )
      
      var (
        mu sync.Mutex
        a  string
      )
      
      func main() {
        mu.Lock()
        go func() {
          a = "hello"
          mu.Unlock()
        }()
        mu.Lock()
        fmt.Printf("%q\n", a)
      }
    5. Predict the output.

      package main
      
      import (
        "fmt"
        "sync"
      )
      
      var (
        once sync.Once
        a    string
        runs int
      )
      
      func setup() {
        runs++
        a = "hello"
      }
      
      func main() {
        var wg sync.WaitGroup
        got := make([]string, 8)
        for i := range got {
          wg.Go(func() {
            once.Do(setup)
            got[i] = a
          })
        }
        wg.Wait()
        fmt.Println(runs, got)
      }
    6. Predict the output.

      package main
      
      import (
        "fmt"
        "sync/atomic"
      )
      
      var (
        a     string
        ready atomic.Bool
      )
      
      func main() {
        go func() {
          a = "hello"
          ready.Store(true)
        }()
        for !ready.Load() {
        }
        fmt.Printf("%q\n", a)
      }
    7. Predict the output.

      package main
      
      import (
        "fmt"
        "sync"
        "sync/atomic"
      )
      
      func main() {
        var n atomic.Int64
        var wg sync.WaitGroup
        for range 8 {
          wg.Go(func() {
            for range 100_000 {
              n.Add(1)
            }
          })
        }
        wg.Wait()
        fmt.Println(n.Load())
      }
    8. Predict the output.

      package main
      
      import (
        "fmt"
        "sync"
        "sync/atomic"
        "time"
      )
      
      func main() {
        limit := make(chan struct{}, 3)
        var now, peak atomic.Int64
        var wg sync.WaitGroup
        for range 40 {
          wg.Go(func() {
            limit <- struct{}{}
            n := now.Add(1)
            for {
              p := peak.Load()
              if n <= p || peak.CompareAndSwap(p, n) {
                break
              }
            }
            time.Sleep(time.Millisecond)
            now.Add(-1)
            <-limit
          })
        }
        wg.Wait()
        fmt.Println("peak:", peak.Load())
      }
    9. Predict the output. The goroutines sleep before they call Add.

      package main
      
      import (
        "fmt"
        "sync"
        "time"
      )
      
      func main() {
        var wg sync.WaitGroup
        var mu sync.Mutex
        total := 0
        for range 3 {
          go func() {
            time.Sleep(5 * time.Millisecond)
            wg.Add(1)
            defer wg.Done()
            mu.Lock()
            defer mu.Unlock()
            total++
          }()
        }
        wg.Wait()
        mu.Lock()
        defer mu.Unlock()
        fmt.Println("total:", total)
      }
    10. Predict the output. Only the type of the flag changed from panel A.

      // The flag is an atomic.Bool. Nothing else changed.
      package main
      
      import (
        "fmt"
        "os"
        "sync/atomic"
        "time"
      )
      
      var done atomic.Bool
      
      func wait() {
        if done.Load() {
          return
        }
        for !done.Load() {
        }
      }
      
      func main() {
        go func() {
          time.Sleep(100 * time.Millisecond)
          done.Store(true)
        }()
        time.AfterFunc(time.Second, func() {
          fmt.Println("1 s later: done =", done.Load(), "and main still spins")
          os.Exit(1)
        })
        wait()
        fmt.Println("main saw done")
      }
    R

    Numbers to say

    measured with testing.B
    load
    1.1 ns plain; 1.1 ns atomic.
    store
    1.4 ns plain; 5.8 ns atomic.
    mutex
    11.4 ns alone.
    -race
    7.5 times the time and 4.0 times the memory on one workload here. Documentation says 2 to 20 and 5 to 10.

    Go 1.27.3, 8-core Intel i9 laptop, GOMAXPROCS 16, median of 3 runs. An atomic load on this CPU is a plain load that the compiler must not remove. Use these as orders of magnitude.