Search code examples
multithreadingcpu-architecturelock-freecpu-cache

CPU Registers and Cache Coherence


What's the relation between CPU registers and CPU cache when it comes to cache coherence protocols such as MESI? If a certain value is stored in the CPU's cache, and is also stored in a register, then what will happen if the cache line will be marked as "dirty"? To my understanding there is no guarantee that the register will update it's value even though the cache was updated (due to MESI).

Hench this code:

 static void Main()  
  {  
  bool complete = false;   
  var t = new Thread (() =>  
  {  
    bool toggle = false;  
    while (!complete) toggle = !toggle;  
  });  
  t.Start();  
  Thread.Sleep (1000);  
  complete = true;  
  t.Join();        // Blocks indefinitely  
}

(let's assume the compiler didn't optimized the load for 'complete' outside the loop)
to my understanding, the update to "complete" isn't visible to the second thread since it's value is held inside a register (CPU 2's cache was update however).

Does placing a memory barrier forces to "flush" all of the registers? What's the relation of registers to the cache? and what about registers and memory barriers?


Solution

  • There is no relationship. Use the "volatile" keyword.