Explain the difference between std::atomic and using a std::mutex. When is an atomic operation not enough to ensure thread safety?

Last updated 21 June 2026

  • std::atomic gives indivisible, often lock-free operations (fetch_add, compare_exchange) on a single variable, plus memory-ordering control. std::mutex serializes 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.

  • https://utkrusht.ai/blog/cplusplus-interview-questions
  • https://roadmap.sh/questions/cpp
  • https://internshala.com/blog/cpp-coding-interview-questions/
All C++ interview questions