gpt4 book ai didi

c# - 单例模式中的双重检查锁定

转载 作者:IT王子 更新时间:2023-10-29 04:37:23 25 4
gpt4 key购买 nike

这可能是个基本问题

要在多线程环境中拥有单例,我们可以使用锁。请引用代码片段。但是为什么我们需要在单例模式中进行双重检查锁定呢?以及更多双重检查锁定意味着什么?

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;
}
}

}
}

最佳答案

乔恩双向飞碟 explains this in detail .

锁很贵。
如果该对象已经存在,则没有必要取出锁。
因此,您在锁外进行了第一次检查。

但是,即使在您查看之前对象不存在,另一个线程也可能在 if 条件和 lock 语句之间创建了它。
因此,您需要再次检查锁内部。

但是,编写单例的最佳方法是使用static 构造函数:

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();
}
}

关于c# - 单例模式中的双重检查锁定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5950418/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com