Golang / GoLang Concurrency Mastery Interview Questions
When should you use the sync/atomic package instead of sync.Mutex?
The sync/atomic package provides lock-free operations on individual primitive values using CPU-level instructions (LOCK prefix on x86, load-linked/store-conditional on ARM). It is faster than a mutex for simple single-variable operations but is limited to supported types and single-variable updates.
import "sync/atomic" // AtomicInt64 Γ’ΒΒ no lock needed var counter int64 atomic.AddInt64(&counter, 1) // atomic increment v := atomic.LoadInt64(&counter) // atomic read atomic.StoreInt64(&counter, 0) // atomic write // Compare-and-Swap (CAS) Γ’ΒΒ the foundation of lock-free algorithms swapped := atomic.CompareAndSwapInt64(&counter, 0, 100) // Sets counter=100 ONLY if counter==0; returns true if swap happened fmt.Println(swapped, atomic.LoadInt64(&counter)) // true 100 // atomic.Value Γ’ΒΒ atomically store/load any interface value var config atomic.Value config.Store(&Config{Timeout: 30 * time.Second}) // must always store same concrete type cfg := config.Load().(*Config) // Performance comparison (approximate, uncontended): // atomic.AddInt64: ~5 ns // sync.Mutex Lock+Unlock: ~25 ns (uncontended) // sync.Mutex Lock+Unlock: ~200 ns (contended) // Use atomic when: // Γ’ΒΒ Simple counters, flags, sequence numbers // Γ’ΒΒ Publishing a single pointer or value others read // Γ’ΒΒ High-frequency metrics (LongAdder / sharded counter pattern) // Use Mutex when: // Γ’ΒΒ Multiple related variables must be updated together atomically // Γ’ΒΒ Non-trivial read-modify-write patterns // Γ’ΒΒ Protecting complex types like maps or slices
Cache-line false sharing: when multiple atomic variables are stored in adjacent memory, a write to one invalidates the CPU cache line of another β degrading performance even though different variables are being modified. Pad hot atomic variables to separate cache lines (64 bytes on x86) in high-performance code.
More Related questions...