1

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);
    }
}
Gary
  • 11
  • 2
  • 3
  • i think these things are orthogonal – Daniel A. White Nov 11 '21 at 01:48
  • "*whether the following code will work as expected,*", they will indeed work as expected, however it depends what you expect, especially considering this is a struct to start with, which has a whole bunch of other expected behaviours – TheGeneral Nov 11 '21 at 01:51

0 Answers0