When would you use the sync/atomic package instead of a mutex, and what are the trade-offs?
Last updated
Use
sync/atomicfor single-value operations (counters, flags, pointer swaps, compare-and-swap), preferably via typed helpers likeatomic.Int64.Use a mutex when several fields or a complex structure must be updated together as one consistent unit.
Atomics are faster (no blocking) but cover only one word, and memory-ordering correctness is subtle. Mutexes are clearer but can block and contend, so use atomics only when profiling justifies it.