Go Atomic Operations vs Mutex
In this tutorial, you'll learn about Go Atomic Operations vs Mutex. We cover key concepts, practical examples, and best practices.
Atomic operations -- Use sync/atomic for lock-free concurrent access to integers, pointers, and booleans.
The Problem
sync.Mutex is heavy for simple integer operations. Atomic operations use CPU-level instructions for fast concurrent access.
Wrong
var counter int64
var mu sync.Mutex
mu.Lock()
counter++
mu.Unlock()
Output:
// Heavyweight for a simple increment
Right
var counter int64
atomic.AddInt64(&counter, 1)
val := atomic.LoadInt64(&counter)
Output:
// Lock-free, CPU-level atomic increment
Prevention
- Use atomic.Add* for counters
- Use atomic.Load/Store for reading/writing
- Use atomic.CompareAndSwap for conditional updates
- Use atomic.Value for lock-free reads of interface{}
- atomic is faster than mutex for simple operations
Common Mistakes with sync atomic
- Using
foldlinstead offoldl'causing stack overflow on large lists - Forgetting
deriving (Show, Eq)on custom data types needed for debugging - Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
These mistakes appear frequently in real-world GO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro. DodaTech tutorials help Go developers build production-ready software used by millions.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro