System Design Academy

Saving…

Lesson 4 of 10 in Module 40 of 45 lessons complete

Atomics & Read-Write Locks

Module 4, lesson 4Concept12 min

Definition

Atomic operation

In plain English
An atomic operation is a single step that other goroutines can never see half-done.
Think of it like
It is like a turnstile clicking the count up by exactly one per person.

Read-write mutex

In plain English
A read-write mutex lets many readers in at once but gives a writer exclusive access.
Think of it like
It is like a museum gallery where crowds can look together, but it closes to everyone while a painting is rehung.

Why it exists

A thousand votes update one total. A museum catalogue receives many more reads than changes.

These access patterns may benefit from specialised tools. Measure them against a plain mutex before assuming they are faster.

How it works

After: every vote uses atomic Add, and main uses Load.
Go
package main

import (
	"fmt"
	"sync"
	"sync/atomic"
)

func main() {
	var votes atomic.Int64
	var wg sync.WaitGroup
	for i := 0; i < 1000; i++ {
		wg.Add(1)
		go func() { defer wg.Done(); votes.Add(1) }()
	}
	wg.Wait()
	fmt.Println(votes.Load())
}
After: readers share access; Reload excludes every reader and writer.
Go
package main

import (
	"fmt"
	"sync"
)

type Catalogue struct {
	mu    sync.RWMutex
	title string
}

func (c *Catalogue) Read() string {
	c.mu.RLock()
	defer c.mu.RUnlock()
	return c.title
}
func (c *Catalogue) Reload(title string) {
	c.mu.Lock()
	defer c.mu.Unlock()
	c.title = title
}
func main() {
	c := &Catalogue{}
	c.Reload("Moon")
	var wg sync.WaitGroup
	for i := 0; i < 3; i++ {
		wg.Add(1)
		go func() { defer wg.Done(); fmt.Println(c.Read()) }()
	}
	wg.Wait()
}
ToolProtectsUseful forWatch for
MutexA protected operationRelated fieldsWaiting holders
RWMutexShared reads or exclusive writesSubstantial read-heavy workExtra coordination cost
AtomicOne atomic operationCounters and flagsSeparate operations leave gaps

Reader 1 and Reader 2 both point to shared read access, while Writer points to exclusive access.

Readers can overlap; a writer needs everyone else outside.

Reader 1 and Reader 2 both point to shared read access, while Writer points to exclusive access.

  • A pending writer blocks new readers until it acquires and releases the RWMutex.
  • Never write under RLock or upgrade RLock to Lock while holding it.
  • Do not copy atomic values or mutexes after first use.

Examples

Count every vote

One total is the entire shared state. You need exactly 1,000 increments.

After: every vote uses atomic Add, and main uses Load.
Go
package main

import (
	"fmt"
	"sync"
	"sync/atomic"
)

func main() {
	var votes atomic.Int64
	var wg sync.WaitGroup
	for i := 0; i < 1000; i++ {
		wg.Add(1)
		go func() { defer wg.Done(); votes.Add(1) }()
	}
	wg.Wait()
	fmt.Println(votes.Load())
}

The result is 1,000. Use atomic operations for every concurrent access to this counter.

The insight

An atomic counter can protect a single total.

Trade-offs

Pros

  • Atomic counters avoid an explicit lock.
  • RWMutex permits overlapping reads.

Cons

  • Separate atomics cannot protect related changes.
  • RWMutex adds coordination overhead.

Use when

  • One independent counter needs updates.
  • Measured read-heavy work benefits from shared reads.

Avoid when

  • Several values must change together.
  • Short or balanced operations favour a plain mutex.

Quick check

Many goroutines increment one counter. Lightest correct tool?
Score and timestamp must always match. Two atomics or one mutex?

Takeaways

  • Use atomic operations for independent counters and flags.
  • Measure before choosing RWMutex for shared reads.
  • Protect related values with one mutex.

Try the quick check above whenever you feel ready.

Previous: Locks & Mutexes