Possible Duplicate:
Why we need Thread.MemoryBarrier()?
From O'Reilly's C# in a Nutshell:
class Foo
{
int _answer;
bool _complete;
void A()
{
_answer = 123;
Thread.MemoryBarrier(); // Barrier 1
_complete = true;
Thread.MemoryBarrier(); // Barrier 2
}
void B()
{
Thread.MemoryBarrier(); // Barrier 3
if (_complete)
{
Thread.MemoryBarrier(); // Barrier 4
Console.WriteLine (_answer);
}
}
}
Suppose methods A and B ran concurrently on different threads:
The author says: "Barriers 1 and 4 prevent this example from writing “0”. Barriers 2 and 3 provide a freshness guarantee: they ensure that if B ran after A, reading _complete would evaluate to true."
My questions are:
- Why Barrier 4 is needed ? Barrier 1 isn't enough ?
- Why 2 & 3 are needed ?
- From what I understand, the barrier prevent executing instructions prior to its location after its following instructions, am I correct ?