1 year ago

#332793

test-img

Petrusion

Will the read/write of the 8 byte struct in these methods be atomic?

I've been learning about atomic operations and C# alignment + atomicity guarantees. I want to see if I understand them correctly. Will the extension methods in the example be atomic, or is there something I'm not taking into account?

I think that other than the situation where the caller used unsafe code to misalign the Point reference in a 64 bit process, they should be atomic, right?

The example:

[StructLayout(LayoutKind.Explicit, Size = 8)]
public struct Point
{
    [FieldOffset(0)]
    public float X;

    [FieldOffset(4)]
    public float Y;
}

public static class PointExtensions
{
    public static Point AtomicRead(this ref Point point)
    {
        unsafe
        {
            // this if will be compiled away
            if(sizeof(Point) != sizeof(long))
            {
                throw new InvalidOperationException($"{nameof(Point)} must be the same size as {nameof(Int64)}");
            }
        }

        long data;

        // this if will be compiled away
        if (Environment.Is64BitProcess)
        {
            /**
             * Optimization to avoid calling cmpxchg8b or similar
             * 
             * If this is a 64 bit process, then reading a long value will be atomic since:
             *  - long is the word size
             *  - JIT ensures fields are aligned and don't straddle cache lines
             *  (this might not be atomic if the caller allocated the Point struct unaligned using unsafe code)
             * 
             * Also:
             * Part below could've been implemented as:
             * data = Unsafe.As<Point, long>(ref point);
             * Thread.MemoryBarrier();
             * 
             * .. but Volatile.Read seems better since it will only place the memory barrier if required
             */
            data = Volatile.Read(ref Unsafe.As<Point, long>(ref point));
        }
        else
        {
            // running 32 bit process, need to use Interlocked/cmpxchg8b to read atomically
            data = Interlocked.Read(ref Unsafe.As<Point, long>(ref point));
        }

        return Unsafe.As<long, Point>(ref data);
    }

    // similar reasoning as in AtomicRead() applies
    public static void AtomicWrite(this ref Point point, Point value)
    {
        unsafe
        {
            // this if will be compiled away
            if (sizeof(Point) != sizeof(long))
            {
                throw new InvalidOperationException($"{nameof(Point)} must be the same size as {nameof(Int64)}");
            }
        }

        if (Environment.Is64BitProcess)
        {
            Volatile.Write(ref Unsafe.As<Point, long>(ref point), Unsafe.As<Point, long>(ref value));
        }
        else
        {
            Interlocked.Exchange(ref Unsafe.As<Point, long>(ref point), Unsafe.As<Point, long>(ref value));
        }
    }
}

c#

optimization

atomic

volatile

0 Answers

Your Answer

Accepted video resources