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 slicesCache-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.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
