When I write a value into a field, what guarantees do I get regarding when the new value will be saved in the main memory? For example, how do I know that the processor don't keep the new value in it's private cache, but updated the main memory?
Another example:
int m_foo;
void Read() // executed by thread X (on processor #0)
{
Console.Write(m_foo);
}
void Write() // executed by thread Y (on processor #1)
{
m_foo = 1;
}
Is there a possibility that after Write() was finished executing, some other thread executes Read() but actually will see "0" as the current value? (since perhaps the previous write to m_foo wasn't flushed yet?).
What kind of primitives (beside locks) are available to ensure the the writes were flushed?
EDIT
In the code sample I've used, the write and read are placed at different method. Doesn't Thread.MemoryBarrier only affect instruction reording that exist in the same scope?
Also, let's assume that they won't be inlined by the JIT, how can I make sure that the value written to m_foo won't be stored in a register, but to the main memory? (or when m_foo is read, it won't get an old value from the CPU cache).
Is it possible to achieve this without using locks or the 'volatile' keyword? (also, let's say I'm not using primitive types, but a WORD sized structs [so volatile cannot be applied].)
uint
and you can applyvolatile
or any other technique discussed in the various answers. – Neilson