3 Aug 2026

Memory models

To understand the memory barriers we first have to look at the hardware level constraints to understand why do they exist, and what do they do at the hardware level.

Cache Coherency protocol:

Store Buffers:

Que: Why store buffers are required?
Ans:

  1. CPU0 wants to modify data from CPU1
  2. CPU0 will be stalled until data arrives from CPU1.
  3. To prevent this unnecessary stalling of writes is to add store buffer.

Process of using the store buffers:

  1. CPU0 records its write in store buffer and continues executing.
  2. when cacheline arrives from CPU1, the data will be moved from store buffer to cache line.
  3. CPU refers to both cache & store buffer to remove any duplicaiton of data.

Invalidation Queues:

Que: Why use invalidation queue?
Ans:

  1. Invalidate messages take long time, cause they have to make sure that the cache line is actually invalidated, that means more work on the CPU.
  2. After Invlidating the cacheline CPU has to send an acknowledgement right away.
  3. This consumes a lot of time, what the hardware does instead is it stores all the invalidate messages in a queue and only when the conserning cache line is used only then does it invalidate and acknowledge the cacheline. This lazy work helps to eliminate CPU stalling.

what to understand from the above hardware architecture?

  1. If we want to write / modify data from cacheline, we have to flush all the data from store buffer into the actual cacheline.
  2. If we want to read data from cacheline, we have to make sure that we have invlidated all the cachelines that were modified by someone else.

Read / Write Memory Barriers:

  1. Read Memory Barrier:
  1. Write Memory Barrier:

Memory Barriers in C++:

Now that we have learnt about the hardware beneath and how it works, we can now focus on the C++ memory barriers, and understand what they do, and when to use one.

std::memory_order_seq_cst (sequential consistency):

std::memory_order_acquire (Read memory Order):

std::memory_order_release (Write memory order):

std::memory_order_acq_release (Read-modify-write):

std::memory_order_relaxed (no fence):

Note: If you have anymore doubts or would like to dive deep into the hardware aspect of Store Buffers and Invlidate Queues, I'll suggest you read the Memory Barriers: a Hardware view for Software Hackers paper, it goes in more detail and will answer most of your questions.

Made with 2026