在单件模式双重检查锁定 [英] double check locking in singleton pattern

查看:159
本文介绍了在单件模式双重检查锁定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是最基本的问题。



要在多线程环境中,我们可以用一个锁单。请参照代码段。但是,为什么我们需要单件模式双重检查锁定?而更多的什么呢双重检查锁定装置?



 类单身
{
私有静态单一实例=空值;
私有静态单(){}

私人静态对象objectlock =新的对象();

公共静态Singleton实例
{
得到
{

锁(objectlock)//单 - 检查锁
{
如果(例如== NULL)
{
实例=新单();
}

返回实例;
}
}

}
}


解决方案

乔恩斯基特解释对此进行了详细



锁是昂贵的。结果
如果该对象已存在,有没有点取出锁。结果
这样,你有一个第一检查锁定之外。



然而,即使你拿了一下之前的对象不存在,另一个线程可能会之间创建它的如果状态和锁定语句。结果
因此,你需要在锁内再次进行检查。



然而,写一个单身的最佳方法是使用静态构造器:

 公共密封类辛格尔顿
{
私人辛格尔顿()
{
}

公共静态Singleton实例{{返回Nested.instance; }}

类的私有嵌套
{
//显式静态构造函数来告诉C#编译器
//没有标记类型beforefieldinit
静态嵌套( )
{
}

内部静态只读Singleton实例=新辛格尔顿();
}
}


it may be basic question

to have a singleton in multi-threaded environment we can use a lock. Please refer the code snippet. But why do we need double-checked locking in singleton pattern? And more what does double-checked locking means?

class singleton
{
    private static singleton instance = null;
    private static singleton() { }

    private static object objectlock = new object();

    public static singleton Instance
    {
        get
        {

            lock (objectlock) //single - check lock
            {
                if (instance == null)
                {
                    instance = new singleton();
                }

                return instance;
            }
        }

    }
}

解决方案

Jon Skeet explains this in detail.

Locks are expensive.
If the object already exists, there's no point in taking out a lock.
Thus, you have a first check outside the lock.

However, even if the object didn't exist before you took the look, another thread may have created it between the if condition and the lock statement.
Therefore, you need to check again inside the lock.

However, the best way to write a singleton is to use a static constructor:

public sealed class Singleton
{
    private Singleton()
    {
    }

    public static Singleton Instance { get { return Nested.instance; } }

    private class Nested
    {
        // Explicit static constructor to tell C# compiler
        // not to mark type as beforefieldinit
        static Nested()
        {
        }

        internal static readonly Singleton instance = new Singleton();
    }
} 

这篇关于在单件模式双重检查锁定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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