单例实例

发布于 2024-09-29 12:49:45 字数 941 浏览 1 评论 0原文

我知道有很多方法可以实现线程安全的单例模式,例如(双重检查锁定、静态只读方法、锁定方法),但当

static void Main(string[] args)
{           
    for (int i = 0; i <= 100; i++)
    {
        Thread t = new Thread(new ParameterizedThreadStart(doSome));
        t.Start(null);               
    }
    Console.ReadLine();
}

private static void doSome(object obj)
{           
    MyReadOnly obj1 = MyReadOnly.getInstance;
    Console.WriteLine(obj1.GetHashCode().ToString());
}   

class MyReadOnly
{
    private static  MyReadOnly instance  = new MyReadOnly();
    int counter = 0;

   // static MyReadOnly()
   // {
   // }  treat is as commented code.

    public static MyReadOnly getInstance { get { return instance; } }
    private MyReadOnly()
    {
        Console.WriteLine((++counter).ToString());
    }       
}

我看到该程序的输出时,我只是尝试了下面的代码,我看到只创建了单个对象(因为相同的哈希码)

如何证明这段代码不是线程安全的?

编辑

删除静态构造函数,这会导致一些混乱

I know there are lot of ways to implement a thread safe singleton pattern like (Double Check Locking , static readonly method, lock method) but i just tried below code

static void Main(string[] args)
{           
    for (int i = 0; i <= 100; i++)
    {
        Thread t = new Thread(new ParameterizedThreadStart(doSome));
        t.Start(null);               
    }
    Console.ReadLine();
}

private static void doSome(object obj)
{           
    MyReadOnly obj1 = MyReadOnly.getInstance;
    Console.WriteLine(obj1.GetHashCode().ToString());
}   

class MyReadOnly
{
    private static  MyReadOnly instance  = new MyReadOnly();
    int counter = 0;

   // static MyReadOnly()
   // {
   // }  treat is as commented code.

    public static MyReadOnly getInstance { get { return instance; } }
    private MyReadOnly()
    {
        Console.WriteLine((++counter).ToString());
    }       
}

when i see the output of this program , i see just single object created (because of same hashcode)

how to prove that this code is not thread safe?

EDIT

removing static constructor which causes some confusion

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

安稳善良 2024-10-06 12:49:45

由于 .NET 中类型初始值设定项的性质,该代码是线程安全的。类型初始值设定项保证只运行一次,如果两个线程尝试同时运行它,一个会执行,另一个会阻塞。

有关更多详细信息,请参阅我的有关单例实现的文章

That code is thread-safe due to the nature of type initializers in .NET. The type initializer is guaranteed to run exactly once, and if two threads try to run it at the same time, one will do so and the other will block.

See my article on singleton implementation for more details.

爱情眠于流年 2024-10-06 12:49:45

这实际上是线程安全的代码,因为您(间接)使用静态构造函数来创建实例(并且 CLR 保证在访问任何其他类型成员时/之前以线程安全的方式调用静态构造函数)。

This is actually thread-safe code because you are (indirectly) using static constructor to create the instance (And CLR guarantees invocation of static constructor is thread-safe manner on/before access to any other type member).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文