Explain the difference between std::atomic and using a std::mutex. When is an atomic operation not enough to ensure thread safety?
Last updated
std::atomicgives indivisible, often lock-free operations (fetch_add,compare_exchange) on a single variable, plus memory-ordering control.std::mutexserializes a whole critical section touching many variables.Atomics are not enough for compound invariants: two individually atomic variables can still be seen in an inconsistent combined state.
They also fail for multi-step operations like
if (a > 0) a--;where check and update aren't atomic together. Use a mutex or a CAS loop.