3

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.

Oday Fraiwan
  • 1,147
  • 1
  • 9
  • 21
  • 1
    Side note: processor does not know anything about C# methods, resulting CPU instructions may not even be a anything resembling method after JIT - i.e. can be inlined. – Alexei Levenkov Oct 14 '14 at 06:06
  • Ok. Then, Does the memor barrier statment still necessary in the above context ? @AlexeiLevenkov – Oday Fraiwan Oct 14 '14 at 06:18
  • 1
    possible duplicate of [Why we need Thread.MemoryBarrier()?](http://stackoverflow.com/questions/3556351/why-we-need-thread-memorybarrier) – Ian Mercer Oct 14 '14 at 06:25
  • The post you cited is asking about the usage of the memory barriers. However, i ask about a specific case whether the barrier statment above is necessary. @IanMercer – Oday Fraiwan Oct 14 '14 at 06:39
  • How is your case different from Barrier#2 in the example? – Ian Mercer Oct 14 '14 at 20:01
  • That example is discussing the use of memory barriers in general, it does not care whether the write statement is the last one or not. The question is, when the write statment is the LAST statement in a method (no other writes are done in the method), is the memory barrier necessary ? @IanMercer – Oday Fraiwan Oct 15 '14 at 08:29
  • There's nothing such as "last". There's just generally endless control and data flow. – Ondrej Tucny Nov 10 '14 at 21:43

1 Answers1

3

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.

Brian Gideon
  • 47,849
  • 13
  • 107
  • 150