Memory Model Guarantees in Double-checked Locking

后端 未结 4 1532
鱼传尺愫
鱼传尺愫 2020-12-30 06:07

I recently came across the following post on the Resharper website. It was a discussion of double-checked locking, and had the following code:

public class F         


        
4条回答
  •  醉酒成梦
    2020-12-30 06:24

    The big problem with the example is that the first null check is not locked, so instance may not be null, but before Init has been called. This may lead to threads using instance before Init has been called.

    The correct version should therefore be:

    public static Foo GetValue()
    {
        if (instance == null)
        {
            lock (padlock)
            {
                if (instance == null)
                {
                    var foo = new Foo();
                    foo.Init();
                    instance = foo;
                }
            }
        }
    
        return instance;
     }
    

提交回复
热议问题