The famous double-checked locking technique in C#

后端 未结 2 1581
小鲜肉
小鲜肉 2021-02-09 22:05

I saw in a mprss book this recommendation of singleton (partial code attached):

public static Singleton GetSingleton() 
{
    if (s_value != null) 
        retur         


        
相关标签:
2条回答
  • 2021-02-09 22:08

    While the assignment is atomic, it is also required that the memory is "synchronized" across the different cores/CPUs (full fence), or another core concurrently reading the value might get an outdated value (outside of the synchronization block). The Interlocked class does this for all its operations.

    http://www.albahari.com/threading/part4.aspx

    Edit: Wikipedia has some useful information about the issues with the double-locking pattern and where/when to use memory barriers for it to work.

    0 讨论(0)
  • 2021-02-09 22:23

    I'll post this not as a real answer but as an aside: if you're using .NET 4 you really should consider the Lazy<T> singleton pattern:

    http://geekswithblogs.net/BlackRabbitCoder/archive/2010/05/19/c-system.lazylttgt-and-the-singleton-design-pattern.aspx

    public class LazySingleton3
    {
       // static holder for instance, need to use lambda to construct since constructor private
       private static readonly Lazy<LazySingleton3> _instance
           = new Lazy<LazySingleton3>(() => new LazySingleton3());
    
       // private to prevent direct instantiation.
       private LazySingleton3()
       {
       }
    
       // accessor for instance
       public static LazySingleton3 Instance
       {
           get
           {
               return _instance.Value;
           }
       }
    

    }

    Thread-safe, easy to read, and obvious: what's not to like?

    0 讨论(0)
提交回复
热议问题