views:

331

answers:

2

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 gurentee 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? whats the relation of registers to the cache? and what about registers and memory barriers?

+4  A: 

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

Hans Passant
A: 

MESI protocol used in x86 platform guarantees cache coherence, i.e. changes in one CPU cache are automatically propagated to other CPU caches. Therefore volatile keyword on x86 and x64 is useful only to prevent reordering.

Vitaliy Liptchinsky
With multiple thread running over multiple cores, volatile won't save you from re-ordering; the different cores will re-order differently and where they're not aware of each others re-ordering choices, volatile can't save you.With multiple threads on one CPU, volatile will ensure the compiler always gets the value of the variable, but i don't think that's quite the same as *not re-ordering*. In fact, I suspect it offers no indications at all about re-ordering behaviour...
Blank Xavier
http://software.intel.com/en-us/blogs/2007/11/30/volatile-almost-useless-for-multi-threaded-programming/
Blank Xavier
This looks like C# code. volatile does have meaning in C# different than in C/C++. I actually think it is a bug in the way MS is building the closure for the thread function. Since complete gets pulled into the closure it should be treated like a global. Would we see the same results (blocks forever) if complete was a global?
tony
volatile also stops the value being cached in a CPU register
Ian Ringrose