Skip to content
Tutorials Center
My learning

Topics

Lesson 69 of 147 ยท Concurrency

Atomic Operations

Learn Go's sync/atomic package - atomic.Int64, Bool and Pointer[T], Add, Load, Store, Swap and CompareAndSwap, CAS loops, atomics versus mutexes and Go's memory ordering.

A mutex protects a section of code. Sometimes, though, the thing you share is just one number or one flag: a request counter, a "shutting down" switch, a pointer to the current configuration. For these, the processor itself offers instructions that read or modify a single memory location in one indivisible step. Such operations are called atomic, and Go exposes them in the package sync/atomic.

Atomics are faster than locks for simple cases and they cannot deadlock, but they are also narrow: they protect exactly one variable at a time. This lesson shows the typed atomics (atomic.Int64, atomic.Bool, atomic.Pointer[T], atomic.Value), the core operations, the compare-and-swap loop, how Go orders memory operations, and when to choose atomics over a mutex.

Atomic counters

The easiest way to use the package is through its types. Since Go 1.19 there are atomic.Int32, atomic.Int64, atomic.Uint32, atomic.Uint64, atomic.Uintptr, atomic.Bool, atomic.Pointer[T] and atomic.Value. Their zero values are ready to use, and their methods do the atomic work:

Go A lock-free counter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The result is always hits: 100000. A plain int64 with hits++ would lose updates here, as explained in data races. Notice you never read an atomic variable with a normal expression: use Load(), which is itself an atomic read.

The basic operations

Every integer type has the same set of methods:

Method What it does
Load() returns the current value
Store(v) sets the value
Add(delta) adds delta and returns the new value
Swap(v) sets v and returns the old value
CompareAndSwap(old, new) sets new only if the value equals old; returns whether it did
And(mask), Or(mask) bitwise operations, return the old value (Go 1.23)
Go Load, Store, Add, Swap and CompareAndSwap

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The output walks through each method: after Store: 10, 15, 12, Swap returned the old value: 12 now: 100, then CAS 100 -> 7: true now: 7 and CAS 100 -> 8: false now: 7 (the second swap fails because the value is no longer 100), and finally Or returned the old value 0101, now 1101. There is no Sub method; to subtract, add a negative number (for unsigned types, add ^uint32(0) for minus one, or better, use a signed type).

The older function style

Before Go 1.19 there were no types. You kept an ordinary int64 variable and called package functions on its address: atomic.AddInt64(&x, 1), atomic.LoadInt64(&x), atomic.CompareAndSwapInt32(&x, old, new) and so on. You will see this in older code, and it is still supported:

Go
var counter int64
atomic.AddInt64(&counter, 1)
fmt.Println(atomic.LoadInt64(&counter))

Prefer the typed form in new code. The typed version cannot be misused by touching the variable with a plain read or write (the field is not even accessible directly), and it guarantees the correct alignment on 32-bit systems, a long-standing trap with 64-bit atomics in the function style.

atomic.Bool: flags and stop signals

A boolean flag shared between goroutines is a very common use. For example, a worker loop can check a "stop" flag that another goroutine sets:

Go A stop flag shared between goroutines

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The program ends with true. The exact number of iterations varies, so the program prints only a comparison. For stopping goroutines, a closed channel or a context is usually better, because a goroutine can block waiting on them. A polling flag only suits loops that already keep running and checking.

atomic.Bool also has Swap and CompareAndSwap, which makes "do this only once" easy: the goroutine whose CompareAndSwap(false, true) returns true is the one that wins.

Go Only one goroutine wins the race to start

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Exactly one goroutine finds the flag at false and flips it, so the output is always winners: 1.

Compare-and-swap loops

CompareAndSwap (CAS) is the building block for any update that is more complex than add or set. The pattern is a loop:

  1. Read the current value.
  2. Compute the new value from it.
  3. Try CompareAndSwap(current, new). If it succeeds, you are done. If it fails, another goroutine changed the value in the meantime, so go back to step 1.

No lock is held; instead, a failed attempt is simply repeated. Here is an atomic "keep the maximum":

Go Tracking a maximum with a CAS loop

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Whatever the order, the final result is highest: 99. If two goroutines try at the same time, one CAS fails and its goroutine retries with the newer value, so the larger value always wins.

CAS loops are only correct when the new value is computed from the old value alone, with no other side effects, because the computation may run several times. They work well under low contention. Under heavy contention many goroutines keep retrying and waste CPU, and a mutex can then be faster.

atomic.Pointer[T]: swapping whole values

atomic.Pointer[T] stores a *T and lets you replace it atomically. This is the right tool for read-mostly data that is replaced as a whole, such as a configuration that is reloaded. Readers always see a complete, consistent object, never a half-updated one, and they do not need any lock:

Go Hot-swapping configuration with atomic.Pointer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The three readers all report v1/safe, because the swap happens only after they finish: [v1/safe v1/safe v1/safe], then replaced version 1 with 2. The rule that makes this safe: never modify a Config after storing it. Build a new value, then publish its pointer. Everyone holding the old pointer keeps a valid, unchanging snapshot until they drop it.

atomic.Value

atomic.Value is the older, untyped relative of atomic.Pointer. It stores any value of one consistent type (the first Store fixes the type; storing a different type panics, and storing nil panics). It needs a type assertion on every Load, so prefer atomic.Pointer[T] unless you must store a non-pointer type:

Go atomic.Value needs a type assertion

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

You see empty: <nil>, then [a b] 2, and finally the panic message recovered: sync/atomic: store of inconsistently typed value into Value. That safety net is another reason to favor the generic, typed atomic.Pointer[T].

Memory ordering in Go

Modern CPUs and compilers reorder memory operations to run faster, and different cores may see writes in different orders. Languages such as C++ expose a menu of "memory orders" for atomics. Go keeps it simple: all atomic operations are sequentially consistent. The Go memory model says that if one atomic operation observes the effect of another, the first is "synchronized after" the second, and everything the writer did before its atomic write is visible to the reader after its atomic read.

In practice, that makes this safe:

Go
var ready atomic.Bool
var data int // ordinary variable

// writer goroutine
data = 42
ready.Store(true)

// reader goroutine
if ready.Load() {
	fmt.Println(data) // guaranteed to print 42
}

The plain write to data happens before ready.Store(true), and the reader only touches data after seeing true. The atomic acts as the "publish" signal for the plain data. That is the same guarantee a channel or a mutex gives, and it is why you do not have to reason about CPU details. The rules are summarized in data races and the memory model.

Atomicity is per variable. Two separate atomic variables do not change together: between updating a and updating b, another goroutine can see the new a with the old b. If an invariant spans several fields, protect them all with one mutex, or put the whole state in one immutable struct and swap it with atomic.Pointer.

Atomics versus mutexes

Situation Better tool
One counter or statistic atomic
A boolean flag or state number atomic
Replace a whole read-mostly value atomic.Pointer[T]
Several variables that must stay consistent mutex
A map, slice or other complex structure mutex
Read-then-act sequences ("if x then y") mutex (or a CAS loop on one variable)
Waiting for a condition channel, sync.Cond

Atomics are not magic speed. They are cheaper than a lock when uncontended, but many goroutines hammering the same atomic still contend for one cache line, so a "sharded" counter (one per goroutine, summed at the end) can be much faster for extremely hot counters. For correctness, use the simplest tool that clearly works, and run tests with the race detector (go test -race) to catch mistakes. See Testing Concurrent Code.

Never mix atomic and plain access to the same variable. If one goroutine uses n.Add(1) while another reads n with a normal expression, that is still a data race. With the typed API, the compiler helps by hiding the raw value.

Go Where a mutex is the right answer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The total stays 1000 at every moment, and at the end checking: 200 savings: 800. Doing the same with two atomics would let another goroutine observe a total of 997 between the two updates.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does n.Add(5) return for an atomic.Int64 currently holding 10?

    Add returns the new value after adding, so 15. Swap and the bitwise And/Or methods return the old value instead.
  2. 2. What does CompareAndSwap(old, new) return?

    CAS compares and, only on a match, stores the new value in one atomic step, reporting success as a bool.
  3. 3. Which tool fits best: two fields balance and limit must always be updated together?

    Atomics protect one variable at a time. Another goroutine could see the first update without the second, so use a mutex (or swap an immutable struct through atomic.Pointer).
  4. 4. What is the rule that makes atomic.Pointer[Config] safe for readers?

    The pointer swap is atomic, but the pointed-to data is not protected. If it is never modified after storing, every reader sees a consistent snapshot.
  5. 5. Which memory ordering do Go's atomic operations provide?

    Go has a single, strong ordering: sequentially consistent. An atomic write publishes everything written before it to a goroutine that observes it with an atomic read.

Summary

  • sync/atomic offers indivisible operations on single variables: typed values Int32, Int64, Uint32, Uint64, Bool, Pointer[T] and Value.
  • Core methods: Load, Store, Add (returns the new value), Swap (returns the old value), CompareAndSwap, plus And and Or (Go 1.23).
  • Prefer the typed API over the older atomic.AddInt64(&x, 1) functions; never mix atomic and plain access to one variable.
  • A CAS loop (read, compute, CompareAndSwap, retry on failure) builds custom updates such as "keep the maximum" without a lock.
  • atomic.Pointer[T] swaps an immutable snapshot of read-mostly data such as configuration.
  • Go's atomics are sequentially consistent, so an atomic write publishes all earlier writes to a goroutine that observes it.
  • Atomics cover one variable only; use a mutex for invariants across several fields or for complex structures.

Next: The context Package shows how to cancel work and set deadlines across goroutines.