一个简单的实现一个Singleton的 [英] A simple implementation of a Singleton

查看:162
本文介绍了一个简单的实现一个Singleton的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这不是一个简单的,以及安全(从而更好)的方式来实现单而不是做双重检查锁定曼波 - JAMBO?这种方法的缺点任何?

 
公共类辛格尔顿
{
    私有静态辛格尔顿_instance;
    私人辛格尔顿(){Console.WriteLine(实例创建); }

    公共静态单例
    {
        得到
        {
            如果(_instance == NULL)
            {
                Interlocked.CompareExchange(REF _instance,新辛格尔顿(),NULL);
            }
            返回_instance;
        }
    }
    公共无效DoStuff(){}
}
 

编辑:的测试线程安全的失败,任何人都可以解释为什么?为什么Interlocked.CompareExchange并不是真正意义上的原子?

 
公共类节目
{
   静态无效的主要(字串[] args)
   {
      的Parallel.For(0,1000000委托(int i)以{Singleton.Instance.DoStuff();});
   }
}

结果(4内核,4个逻辑处理器)
实例创建
实例创建
实例创建
实例创建
实例创建
 

解决方案

我不相信你能完全信任。是的,Interlocked.CompareExchanger是原子,但新辛格尔顿()是不会是原子在任何不平凡的情况。因为它具有交换价值前评估,这不会是一般的线程安全的实现。

Isn't this a simpler as well as safe (and hence better) way to implement a singleton instead of doing double-checked locking mambo-jambo? Any drawbacks of this approach?


public class Singleton
{
    private static Singleton _instance;
    private Singleton() { Console.WriteLine("Instance created"); }

    public static Singleton Instance
    {
        get
        {
            if (_instance == null)
            {
                Interlocked.CompareExchange(ref _instance, new Singleton(), null);
            }
            return _instance;
        }
    }
    public void DoStuff() { }
}

EDIT: the test for thread-safety failed, can anyone explain why? How come Interlocked.CompareExchange isn't truly atomic?


public class Program
{
   static void Main(string[] args)
   {
      Parallel.For(0, 1000000, delegate(int i) { Singleton.Instance.DoStuff(); });
   }
} 

Result (4 cores, 4 logical processors)
Instance created
Instance created
Instance created
Instance created
Instance created

解决方案

I am not convinced you can completely trust that. Yes, Interlocked.CompareExchanger is atomic, but new Singleton() is in not going to be atomic in any non-trivial case. Since it would have to evaluated before exchanging values, this would not be a thread-safe implementation in general.

这篇关于一个简单的实现一个Singleton的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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