sync/atomic and lock-free counters

sync/atomic gives a small set of operations that a CPU performs as one step: add, load, store, swap and compare-and-swap. No lock is taken, nothing blocks, and the result is the same as if the operations ran one after another. The cost is that only one variable is protected at a time, so the atomic package fixes counters and flags, not invariants across several fields.

An atomic counter

The same thousand goroutines as the mutex lesson, with atomic.Int64 instead of a lock. Add returns the new value, Load reads it, and the zero value is a counter at zero, ready to use. The total is right every time and no goroutine waits for another.

package main import ( "fmt" "sync" "sync/atomic" ) func main() { var counter atomic.Int64 var wg sync.WaitGroup for i := 0; i < 1000; i++ { wg.Add(1) go func() { defer wg.Done() counter.Add(1) }() } wg.Wait() fmt.Println("count:", counter.Load()) }

go build -o app main.go && ./app

count: 1000

The typed form, atomic.Int64, exists so a counter cannot be copied and used through a plain int64 by mistake: the field is a struct with the value inside and the methods are the only way to touch it. atomic.AddInt64(&n, 1) on a bare int64 still works and is what the typed form wraps.

CompareAndSwap

CompareAndSwap(old, new) writes new only if the current value is still old, and reports whether it did. That is the primitive for a read-modify-write that cannot be expressed as a single Add: the program reads, computes, and tries to swap; if another goroutine changed the value in between, the swap fails and the loop retries with the new value.

package main import ( "fmt" "sync" "sync/atomic" ) func main() { var value atomic.Int64 value.Store(10) var wg sync.WaitGroup for i := 0; i < 3; i++ { wg.Add(1) go func() { defer wg.Done() for { old := value.Load() if value.CompareAndSwap(old, old*2) { fmt.Println("doubled", old) return } } }() } wg.Wait() fmt.Println("value:", value.Load()) }

go build -o app main.go && ./app

doubled 10
doubled 20
doubled 40
value: 80

Ten doubled three times is eighty, and the three lines can come in any order: a run printed 10, 40, 20 with the same final value. A CAS loop is correct only if the value is not changed by anything that does not use the same loop, and it can spin forever under heavy contention, which is why an Add is preferred when the operation is an Add.

atomic.Bool

atomic.Bool is a flag with the same five operations. Swap writes a value and returns the old one, and CompareAndSwap flips it only if it still holds the expected value, which is how a program elects one winner: the goroutine whose swap returns true is the one that does the work.

package main import ( "fmt" "sync/atomic" ) func main() { var ready atomic.Bool fmt.Println("before:", ready.Load()) ready.Store(true) fmt.Println("after:", ready.Load()) fmt.Println("swap:", ready.Swap(false), ready.Load()) fmt.Println("cas:", ready.CompareAndSwap(false, true), ready.Load()) }

go build -o app main.go && ./app

before: false
after: true
swap: true false
cas: true true

The swap returned the value it replaced, which is why the printed pair is true false. The CompareAndSwap found false and wrote true, so it returned true and the load after it is true. A zero atomic.Bool is false, so a struct field needs no initialisation.

atomic.Pointer

atomic.Pointer[T] stores a pointer to a value a program reads without locking. The usual pattern is an immutable configuration: a writer builds a whole new struct, stores the pointer, and readers load the pointer and use the struct it names. A reader sees either the old configuration or the new one, never a half-written mix, because the struct it points to is never modified.

package main import ( "fmt" "sync/atomic" ) type Config struct { Name string } func main() { var current atomic.Pointer[Config] current.Store(&Config{Name: "first"}) fmt.Println("read:", current.Load().Name) next := &Config{Name: "second"} current.Store(next) fmt.Println("read:", current.Load().Name) }

go build -o app main.go && ./app

read: first
read: second

The atomic operations order memory: a Store happens before a Load that sees it, which is what makes the fields of the new Config visible to the reader. The Go memory model is the formal statement of that rule; the practical rule is that an atomic variable carries its own payload and everything that payload points to must be immutable once published.

Exercises

  1. Replace the atomic counter with a plain int and run under -race. Which two accesses does the detector name?
  2. Add a second goroutine that also doubles the value and run the CAS program several times. Can the final value be anything other than 80? What would a lost CAS retry look like?
  3. Use atomic.Pointer to publish a slice of settings and print it from a reader goroutine. Why must the slice not be appended to after the Store?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does atomic.Int64.Add do?

    Answer

    Adds and returns the new value as one step

    No other goroutine can observe a half-finished add.

  2. What does CompareAndSwap(old, new) do?

    Answer

    Writes new only if the value is still old

    It reports whether the write happened.

  3. Why does a CAS loop retry?

    Answer

    The value changed between the load and the swap

    The retry recomputes from the new value.

  4. What does atomic.Bool.Swap return?

    Answer

    The previous value

    The caller learns what it replaced.

  5. What is the zero value of atomic.Bool?

    Answer

    false

    A struct field needs no initialisation.

  6. What does atomic.Pointer store?

    Answer

    A pointer that can be loaded and stored atomically

    Readers see one whole version or another.

  7. Why must the pointed-to value be immutable?

    Answer

    So a reader never sees a half-written struct

    The atomic only protects the pointer, not the contents.

  8. What does an atomic operation guarantee about memory?

    Answer

    That a store is visible before a load that sees it

    The Go memory model defines the order.

  9. When is a mutex better than atomics?

    Answer

    When several fields must change together

    An atomic protects one variable at a time.

  10. What can a CAS loop do under heavy contention?

    Answer

    Spin and retry many times

    That is why Add is preferred for a counter.

The code on this page was run with go 1.26.10 on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev