Atomic Operations
You'll learn what atomic operations are and why they're essential for writing safe concurrent code.
What Are Atomic Operations?
An atomic operation is an indivisible unit of work that executes completely without interruption from other threads. From any thread's perspective, an atomic operation either hasn't started or has fully completed—there's no observable "in-between" state.
Think of it like a door that automatically locks when you open it: no one else can open the door while you're stepping through. Either the door is closed (operation hasn't started) or you're completely on the other side (operation finished). No one can slip through halfway.
Why Atomic Operations Matter
Remember race conditions in critical sections? They occur when multiple threads access shared data and at least one modifies it. Without protection, you get inconsistent results because operations like counter++ actually involve multiple steps (read, increment, write).
Atomic operations solve this by guaranteeing that common operations execute as a single, uninterruptible step. When Thread A performs an atomic increment on a counter, Thread B cannot observe the counter in a partially-updated state.
Common Atomic Operations
Most languages and hardware provide atomic versions of basic operations:
- Read/Write: Get or set a value atomically
- Compare-and-Swap: Update only if current value matches expected value
- Increment/Decrement: Adjust numeric values atomically
- Exchange: Swap values atomically
These primitives let you protect shared data without the overhead of locks in many scenarios.
Key Takeaway: Atomic operations execute as indivisible units, preventing race conditions by ensuring threads never observe partial updates—they're the building blocks for lock-free concurrent programming.