Skip to content

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.

  • sync1sync.Mutex to guard a shared counter
  • sync2sync.Once for run-exactly-once initialization
  • sync3sync/atomic for a lock-free counter

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++

Source

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++ })

Source

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)

Source