Sync
Advanced · Concurrency
The sync and sync/atomic packages coordinate goroutines that share memory.
Always test concurrent code with go test -race (this repo’s mise run test
does) — it flags data races the eye misses.
- sync1 —
sync.Mutexto guard a shared counter - sync2 —
sync.Oncefor run-exactly-once initialization - sync3 —
sync/atomicfor a lock-free counter
Resources
Section titled “Resources”Exercises
Section titled “Exercises”sync1 test
Section titled “sync1 test”A sync.Mutex guards shared state so concurrent goroutines don’t race.
Show hint
Guard the critical section:
c.mu.Lock()defer c.mu.Unlock()c.n++sync2 test
Section titled “sync2 test”sync.Once runs a function exactly once, even when called from many goroutines.
Show hint
sync.Once.Do runs its function only the first time it is called:
c.once.Do(func() { c.loads++ })sync3 test
Section titled “sync3 test”sync/atomic provides lock-free atomic operations on integers — cheaper than
Show hint
Increment without a lock using an atomic operation:
atomic.AddInt64(&hits, 1)