Search code examples
c#.netmultithreadingdnxmemory-barriers

Thread.MemoryBarrier() and other memory fences capabilities in DNX Core 5.0


As far as I'm understanding those trick things, being able to do a full full fence memory barrier is more important on DNX than in standard .Net framework: - DNX could possibly run on IA64 that has a weaker memory model than x86/x64. - the Microsoft CLR uses a stronger memory model than the ECMA specification defines.

Quoting from the answer of Why do I need a memory barrier?

You are going to have a very hard time reproducing this bug. In fact, I would go as far as saying you will never be able to reproduce it using the .NET Framework. The reason is because Microsoft's implementation uses a strong memory model for writes. That means writes are treated as if they were volatile. A volatile write has lock-release semantics which means that all prior writes must be committed before the current write.

However, the ECMA specification has a weaker memory model. So it is theoretically possible that Mono or even a future version of the .NET Framework might start exhibiting the buggy behavior.

However, neither MemoryBarrier, VolatileRead and VolatileWrite are available on Thread class.

My questions are:

  • Is this a definitive choice?
  • What is the best alternative (providing my current code base uses MemoryBarrier) to implement lock-free stuff?

Solution

  • Actually the Thread.MemoryBarrier() method has been moved to Interlocked.MemoryBarrier().

    This Interlocked method is available on .Net 4.5 (and 4.6) and on DNXCORE50: this is definitely the one to use from now on.

    Note that VolatileRead\Write are not available.