Skip to Content
Skip to content
Go Advanced: Performance, Concurrency, and Production
Advanced
Courses
Go Advanced: Performance, Concurrency, and Production

Coordinate Shared State With sync.Mutex and atomic

Protect shared counters and maps with sync.Mutex or sync/atomic, keep lock hold times short, and verify with -race. After this, you can choose between mutexes, atomics, and channels cleanly.

Course content

Sign in to save your progress.

Course Home

Suppose your API gateway maintains two pieces of shared in-memory state across 1,000 concurrent request goroutines: a total requestCount metric, and a feature-flag map reloaded from a database every 30 seconds. Most developers assume sync.RWMutex always beats sync.Mutex when reads outnumber writes 99-to-1—until they actually benchmark it.

In this lesson, you will measure sync.Mutex, sync.RWMutex, and sync/atomic head-to-head on Go 1.27, see why RWMutex bounces CPU cache lines on short reads, and learn how atomic.Pointer[T] swaps whole read-only configs with zero locks.

Skip ahead

If you already choose between sync.Mutex, sync.RWMutex, atomic.Int64, and atomic.Pointer[T] based on critical-section duration and know why recursive RLock deadlocks, take the section quiz or move on to "Measure Speed and Allocations With go test -bench."

Experiment 1: Benchmarking 99% reads / 1% writes in parallel

Run all three synchronization primitives under parallel load where 99% of operations are reads and 1% are writes:

func BenchmarkMutexRead99(b *testing.B) {
	var mu sync.Mutex
	var v int64
	b.RunParallel(func(pb *testing.PB) {
		i := 0
		for pb.Next() {
			i++
			mu.Lock()
			if i%100 == 0 {
				v++
			} else {
				_ = v
			}
			mu.Unlock()
		}
	})
}

func BenchmarkRWMutexRead99(b *testing.B) {
	var mu sync.RWMutex
	var v int64
	b.RunParallel(func(pb *testing.PB) {
		i := 0
		for pb.Next() {
			i++
			if i%100 == 0 {
				mu.Lock()
				v++
				mu.Unlock()
			} else {
				mu.RLock()
				_ = v
				mu.RUnlock()
			}
		}
	})
}

func BenchmarkAtomicRead99(b *testing.B) {
	var v atomic.Int64
	b.RunParallel(func(pb *testing.PB) {
		i := 0
		for pb.Next() {
			i++
			if i%100 == 0 {
				v.Add(1)
			} else {
				_ = v.Load()
			}
		}
	})
}
$ go test -bench=. -benchmem -benchtime=200ms
BenchmarkMutexRead99-2     	27176330	         9.073 ns/op	       0 B/op	       0 allocs/op
BenchmarkRWMutexRead99-2   	27857293	         8.188 ns/op	       0 B/op	       0 allocs/op
BenchmarkAtomicRead99-2    	491158420	         0.4812 ns/op	       0 B/op	       0 allocs/op

Experiment 2: Why RWMutex barely beat Mutex while atomic.Int64 won by 17x

Look closely at the hardware reason behind those numbers:

  1. mu.RLock() and mu.RUnlock() still perform atomic writes to an internal shared reader counter inside the RWMutex struct. When multiple CPU cores call RLock() concurrently for a 2-nanosecond read, they fight over ownership of that exact same cache line!
  2. v.Load() on atomic.Int64 performs a pure read with zero writes to any lock word, so all cores keep the cache line in shared read mode—running at 0.48 ns/op.
  3. sync.RWMutex only pulls decisively ahead when readers hold the lock for microseconds or longer (for example scanning a 500-item slice or copying a large map) so concurrent readers do real work in parallel while writes remain rare.

Experiment 3: Lock-free config reloads with atomic.Pointer[T]

For our API gateway's feature-flag map—read on every single request, refreshed every 30 seconds—you can get zero lock contention on reads by building a brand-new immutable map on reload and swapping the pointer atomically:

var flags atomic.Pointer[map[string]bool]

// Background refresher builds a fresh map and swaps atomically:
next := map[string]bool{"new_checkout": true}
flags.Store(&next)

// Request handler reads lock-free (never mutate the returned map!):
if m := flags.Load(); m != nil && (*m)["new_checkout"] {
	// ...
}

Experiment 4: Why recursive RLock() and lock upgrades deadlock

Suppose Goroutine A holds mu.RLock() and calls a helper function that also calls mu.RLock(). If Goroutine B calls mu.Lock() in between those two lines, Go's RWMutex immediately blocks all new readers so writers never starve—meaning Goroutine A's second RLock() waits for B, while B waits for A's first RUnlock(). Instant deadlock! The same happens if two readers try to "upgrade" RLock() to Lock(). Never call RLock() recursively; release RUnlock() first, acquire Lock(), and re-check the state.

Common mistakes

  • Protecting two linked fields with two separate atomic.Int64 variables: Another goroutine can observe field A updated and field B stale. Whenever multiple fields share an invariant, use one sync.Mutex.
  • Copying a struct containing a sync.Mutex by value: Copies the lock state and breaks mutual exclusion; always pass pointers (*Store) and watch go vet warnings.
  • Mutating a map after publishing it with atomic.Pointer: Causes an immediate concurrent-map data race; always build a fresh map and call Store.

💡 Tip

Prefer Go 1.19+ typed atomics (atomic.Int64, atomic.Bool, atomic.Pointer[T]) over raw atomic.AddInt64(&x, 1)—they make accidental non-atomic reads impossible at compile time.

What happens if you skip this step

Using RWMutex reflexively adds deadlock risks (recursive read locks) and cache-line contention with zero speedup on small reads; splitting multi-field invariants across atomics creates subtle half-updated state bugs under heavy concurrency.

Goroutine A calls mu.RLock(), then calls a helper that calls mu.RLock() again on the same sync.RWMutex, while Goroutine B calls mu.Lock() in between. Why does the program deadlock?

About

Protect shared counters and maps with sync.Mutex or sync/atomic, keep lock hold times short, and verify with -race. After this, you can choose between mutexes, atomics, and channels cleanly.

Duration
5 min
Last update
11/27/2026
Was this helpful?
​ 0 ​ 0

Comments

Sign in to comment

No comments yet.