I am trying to atomically assign two 32-bit values in C#. I have came up with a solution using FieldOffset
on a struct
and the 64-bit version of the Interlocked
methods. I am wondering whether the following code will work as expected, or if any CPU register/cache level shenanigans will cause unexpected behaviors.
[StructLayout(LayoutKind.Explicit)]
struct Union
{
[FieldOffset(0)] int value0;
[FieldOffset(4)] int value1;
[FieldOffset(0)] long both;
public int Replace0(int replacement0) => Interlocked.Exchange(ref value0, replacement0);
public int Replace1(int replacement1) => Interlocked.Exchange(ref value1, replacement1);
public void ReplaceBoth(int replacement0, int replacement1)
{
//When using this method, the combination of value0 and value1 should not shear
var union = new Union { value0 = replacement0, value1 = replacement1 };
Interlocked.Exchange(ref both, union.both);
}
}