Atomic Operations and Memory Models
In the previous two chapters, we discussed thread lifecycles and mutex synchronization mechanisms—solving the fundamental problem of "how to make multiple threads cooperate safely." However, mutexes come with an inherent cost: even for a simple increment of a single variable in a critical section, we must go through the full lock → modify → unlock sequence. When performance requirements are higher and critical sections are smaller, we need lighter-weight tools.
In this chapter, we dive into the world of std::atomic and the C++ memory model. std::atomic leverage CPU atomic instructions to guarantee the indivisibility of operations without locking. Memory order controls instruction reordering behavior by the compiler and CPU, allowing us to make precise trade-offs between performance and predictability. Together, these two form the theoretical foundation of lock-free programming—prerequisite knowledge for the lock-free data structures and atomic operation patterns discussed in subsequent chapters.