before I start I just want to acknowledge that I am aware there are questions about this before that I've linked below:
Why do I need a memory barrier?
Why we need Thread.MemoryBarrier()?
That said... I've read both and still don't quite understand what's going on from the basic level.
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);
}
}
}
This code snippet is taken from C# 4.0 in a Nutshell. Currently, I understand the problem without memory barriers is that there's a possibility that B will run before A and B will print nothing because _complete could be evaluated as false.
The "barriers" in each function are completely separate with each other and it's not like the barriers are ordered... Thread.MemoryBarrier(1) or anything so the compiler doesn't know A should go before B.
Could someone clear this up for me? Thanks
EDIT: I think I'm confused about how instruction ordering works... but I'm so confused about the topic that I'm not even sure how to phrase my question appropriately.