Atomics & Read-Write Locks
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
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())
}
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()
}
| Tool | Protects | Useful for | Watch for |
|---|---|---|---|
| Mutex | A protected operation | Related fields | Waiting holders |
| RWMutex | Shared reads or exclusive writes | Substantial read-heavy work | Extra coordination cost |
| Atomic | One atomic operation | Counters and flags | Separate operations leave gaps |
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.
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.
Share catalogue reads
Visitors read exhibit names throughout the day. A nightly reload replaces the catalogue.
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()
}
Read returns a string value. Returning an internal mutable map would let callers bypass the lock.
The insight
RWMutex can help when substantial reads greatly outnumber writes.
Keep score and time together
A score and its timestamp must match. The demo represents time as a numbered update tick.
package main
import (
"fmt"
"sync/atomic"
)
func main() {
var score, stamp atomic.Int64
score.Store(1)
fmt.Println("reader sees", score.Load(), stamp.Load())
stamp.Store(1)
}
package main
import (
"fmt"
"sync"
)
type Board struct {
mu sync.Mutex
score, stamp int
}
func (b *Board) Update() { b.mu.Lock(); defer b.mu.Unlock(); b.score++; b.stamp++ }
func (b *Board) Read() (int, int) { b.mu.Lock(); defer b.mu.Unlock(); return b.score, b.stamp }
func main() {
b := &Board{}
var wg sync.WaitGroup
wg.Add(1)
go func() { defer wg.Done(); b.Update() }()
wg.Wait()
fmt.Println(b.Read())
}
The Before program stages a possible reader observation between writes. The race detector cannot diagnose this logical mismatch.
The insight
Related values need one protected operation.
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
Takeaways
- Use atomic operations for independent counters and flags.
- Measure before choosing RWMutex for shared reads.
- Protect related values with one mutex.