正在访问在C#中的变量一个原子操作? [英] Is accessing a variable in C# an atomic operation?

查看:142
本文介绍了正在访问在C#中的变量一个原子操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经提高到相信,如果多个线程可以访问一个变量,那么所有的读取和写入该变量必须由同步code的保护,如锁定的声明,因为处理器可能通过写切换到另一个线程一半。

I've been raised to believe that if multiple threads can access a variable, then all reads from and writes to that variable must be protected by synchronization code, such as a "lock" statement, because the processor might switch to another thread halfway through a write.

不过,我一直在寻找通过System.Web.Security.Membership使用反射,发现code是这样的:

However, I was looking through System.Web.Security.Membership using Reflector and found code like this:

public static class Membership
{
    private static bool s_Initialized = false;
    private static object s_lock = new object();
    private static MembershipProvider s_Provider;

    public static MembershipProvider Provider
    {
        get
        {
            Initialize();
            return s_Provider;
        }
    }

    private static void Initialize()
    {
        if (s_Initialized)
            return;

        lock(s_lock)
        {
            if (s_Initialized)
                return;

            // Perform initialization...
            s_Initialized = true;
        }
    }
}

为什么s_Initialized场读锁之外吗?无法另一个线程试图在同一时间来写呢? 的读取和写入的变量原子?

推荐答案

对于明确的答案去规范。 :)

For the definitive answer go to the spec. :)

分区我的CLI规范规定第12.6.6:一个符合CLI须保证读写访问正确对齐的内存位置并不比本地字大小是原子当所有的写访问的位置都较大相同的大小。

Partition I, Section 12.6.6 of the CLI spec states: "A conforming CLI shall guarantee that read and write access to properly aligned memory locations no larger than the native word size is atomic when all the write accesses to a location are the same size."

所以这证实s_Initialized永远是不稳定的,而读取和写入primitve类型小于32位原子操作。

So that confirms that s_Initialized will never be unstable, and that read and writes to primitve types smaller than 32 bits are atomic.

在特别双击的Int64 UINT64 )的不可以保证是在32位平台上的原子。您可以使用在互锁类的方法来保护这些。

In particular, double and long (Int64 and UInt64) are not guaranteed to be atomic on a 32-bit platform. You can use the methods on the Interlocked class to protect these.

此外,同时读取和写入原子,有一个与加法,减法和递增和递减的原始类型,因为它们必须读取的竞争条件,手术和改写。 Interlocked类允许您使用 CompareExchange 递增的方法来保护这些。

Additionally, while reads and writes are atomic, there is a race condition with addition, subtraction, and incrementing and decrementing primitive types, since they must be read, operated on, and rewritten. The interlocked class allows you to protect these using the CompareExchange and Increment methods.

联锁创建一个记忆障碍prevent处理器重新排序的读取和写入。锁创建在本实施例唯一必需的屏障

Interlocking creates a memory barrier to prevent the processor from reordering reads and writes. The lock creates the only required barrier in this example.

这篇关于正在访问在C#中的变量一个原子操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆