这些方法中 8 字节结构的读/写是否是原子的?

发布于 2025-01-17 03:07:35 字数 2664 浏览 1 评论 0原文

我一直在学习原子操作和 C# 对齐 + 原子性保证。我想看看我是否正确理解它们。示例中的扩展方法是原子的,还是有什么我没有考虑到的?

我认为除了调用者使用不安全代码在 64 位进程中错位 Point 引用的情况之外,它们应该是原子的,对吗?

例子:

[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));
        }
    }
}

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(
quot;{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(
quot;{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));
        }
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文