Search code examples
c#multithreadingmemory-barriers

C# Memory Barriers


I have a question about memory barriers in C#. If a write statment is the last statement in a method, for example (the variable v2 is the one of concern):

int _v1 = 0;
int _v2 = 0

void X()
{
    _v1 = 2;
    _v2 = 3;
   Thread.MemoryBarrier();
}

Is the memory barrier statment necessary as the _v2 write is the last statement. In other words, does the processor recognize that this is the end of a method and should flush its cache to the memory.

Thanks in advance.


Solution

  • If you want a memory barrier to exist after the write to _v2 then you should keep the call to Thread.MemoryBarrier as-is. I have not seen any documentation that would suggest that a memory barrier is automatically injected after a method ends. If it is not documented then you have to assume that the C# compiler, JIT compiler, and hardware are all given maximum liberty in optimizing the code as they see fit even though in reality their options may be constrained by implementation details.