Atomic operations
Атомарные операции
An operation is atomic if it appears to other threads as one indivisible step. An atomic increment, for example, lets two threads update the same counter without losing either increment.
Also known as: atomic, CAS
What atomic means
An atomic operation takes effect as a single step from the point of view of other threads accessing the same variable. That doesn't mean the thread can't be paused or that the operation takes one CPU instruction. It means other threads can't observe a partially completed change. The guarantee applies to a specific operation, not to the line of source code that contains it.
Why an increment can go wrong
An increment usually has three logical steps: read the current value, add one, and write the result. Start at 10 and let two threads read before either writes. Both compute 11 and both write 11, even though the result should be 12. Making the read and write individually atomic still allows that sequence. An atomic read-modify-write operation, such as fetch_add, makes the entire update indivisible.
#include <atomic>
std::atomic<unsigned> requests{0};
void record_request() {
requests.fetch_add(1, std::memory_order_relaxed);
}
If 100 calls to record_request() finish, they contribute 100 increments. In C++, memory_order_relaxed is enough for this counter because it preserves atomicity. It doesn't, however, make the counter a safe way to tell another thread that separate request data is ready to read. That's a memory-ordering question, not a question of whether the increments get lost.
Where compare-and-swap fits
Compare-and-swap (CAS) is an atomic operation that replaces a value only if it still matches an expected value. Suppose a shared quota has one slot left. Two threads may both read 1, but only one can use CAS to change 1 to 0 before a slot is returned. The other must check the current value again instead of assuming it reserved a slot. CAS is useful for conditional updates like this; it's not another name for every atomic operation.
When to use atomics instead of a mutex
Atomics are useful for independent counters, status flags, and the internals of nonblocking data structures. They aren't automatically faster than a mutex: many threads updating the same variable can still contend, and an atomic operation isn't necessarily implemented without locks. When several fields must stay consistent, a mutex is often easier to reason about. Every reader and writer that relies on that consistency must follow the same locking rule.
What interviewers look for
A common question is whether two atomic calls make a thread-safe check-then-act sequence. Walk through a concrete interleaving: both threads see a free slot, then both decrement the count. Explain that the check and update must be protected together, for example with CAS on a single counter or with a mutex around the whole critical section.