In this lesson, you will learn how the MESI protocol acts as a "traffic controller" to keep data consistent when multiple CPU cores share a memory system.
The Challenge of Private Caches
When we use multi-level cache hierarchies, each core typically has its own private L1 cache. If Core A and Core B both load the same variable from main memory, they each store a copy. If Core A modifies its copy, Core B is left with "stale" (outdated) data. Without a coherence protocol, the system would produce incorrect results.
The MESI Protocol
The MESI protocol manages this by assigning one of four states to every cache line. The acronym stands for:
- M (Modified): The cache line is present only in this cache and has been modified (it is "dirty"). The core is responsible for writing it back to memory eventually.
- E (Exclusive): The cache line is present only in this cache and matches main memory (it is "clean").
- S (Shared): The cache line is present in this cache and potentially other caches. It matches main memory.
- I (Invalid): The cache line is unused or obsolete.
How it Works in Practice
Imagine both cores have the variable x in their cache in the Shared (S) state. If Core A decides to update x:
x = 10; // Core A execution
- Core A broadcasts an "invalidate" signal on the system bus.
- Core B receives this signal and changes its copy of
xto the Invalid (I) state. - Core A transitions its copy of
xto the Modified (M) state. - If Core B tries to read
xagain, it will trigger a "cache miss," see that Core A has the modified data, and pull the updated value.
By forcing caches to "talk" to each other via these state transitions, the hardware ensures that no core performs computation on stale data, maintaining a single view of memory despite the physically distributed caches.
Key Takeaway: The MESI protocol maintains data consistency by tracking the state of each cache line across all cores, ensuring that any write operation either invalidates or updates all other copies of that data.