Are assignment of 4-byte quantities guaranteed atomic in the CLR?

We had a little thread on this internally today and I thought it interesting enough to share here. I am just experimenting here – is this type of thing useful?

Q: If I do simple Int32 assignment to a shared variable in a CLR multi-threaded app, do I need to implement a lock. The Interlocked class has many static methods, but no "assignment" (although Exchange works well enough -- even if it seems a little kludgey).

A: (From one of the senior architects on the CLR team)

The assignment will be atomic so long as the 4-byte quantity is 4-byte aligned.

If you allow the CLR to perform the layout (AutoLayout) then we will guarantee that alignment and hence the atomicity. If you use ExplicitLayout or SequentialLayout, then you are responsible for alignment. So long as you use the default packing, even SequentialLayout will guarantee good alignment.

Of course, guaranteeing an atomic update is not the same thing as guaranteeing that the other CPUs will immediately see the value you wrote. Using Interlocked.Exchange will make this latter guarantee.

 

 

Update: A reader points out you can find more information about this in ECMA 335 spec (section: The Atomicity of Memory Accesses).