C # Memory Barriers

I have a question about memory barriers in C #. If the record is the last statement in the method, for example (the v2 variable is the problem):

int _v1 = 0;
int _v2 = 0

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

      

Whether the memory protection status is required because the _v2 entry is the last one. In other words, whether the processor recognizes that this is the end of the method and should flush its cache into memory.

Thanks in advance.

+3


source to share


1 answer


If you want the memory barrier to exist after writing to _v2

, you must save the call Thread.MemoryBarrier

as it is. I have not seen any documentation that would suggest that a memory barrier is automatically introduced after a method completes. If this is not documented, you should assume that the C # compiler, JIT compiler, and hardware have the maximum freedom to optimize the code as they see fit, even if in fact their options may be limited by implementation details.



+3


source







All Articles