C# – Memory barriers and large structs

cmemory-barriersmemory-modelmultithreadingvolatile

Let's say I've got a struct that consist of 100 bytes. What guarantees have I got about the following code?

m_myLargeStruct = someValue; // copying 100 bytes
Thread.MemoryBarrier();

// Executed by another thread, after "Thread.MemoryBarrier" was called by the first thread
Console.WriteLine(m_myLargeStruct.ToString());

Does the memory model guarantee that the 100 bytes copy will be complete after the placement of the memory barrier? or do memory barriers only apply for types that are at the size of the processor's architecture? (4 bytes for 32bit and 8 bytes to 64bit).
Is this the reason why the volatile keyword only applies for primitive types? (if i declare an 8 byte member as volatile, this means that an interlocked instrinct will be used to change it's value? [since atomicity isn't guaranteed for types larger than 4 bytes on 32bit machines]).

I hope I was clear enough.. 🙂
Thanks

Best Answer

Unless the reading thread has a memory barrier too, I don't think it'll help you much.

Personally I would shy away from:

  • Structs that are that big
  • Getting deeply into the memory model to write lock-free code

... unless you have a really important reason to do so. It's hugely hard to get lock-free coding right with mutable data; I believe that even the experts struggle. I usually find that the "take a lock out for every block accessing the data" approach is easier to get right and is fine in terms of performance for 99% of cases.

I trust the PFX team at Microsoft to get lock-free coding right, and for them to provide me wth ways I can use their code to write my own lock free programs relatively easily. I don't trust myself to get this sort of thing right. If I ever need to explicitly use a memory barrier, that probably means I'm trying too hard.

Related Topic