单例实例
我知道有很多方法可以实现线程安全的单例模式,例如(双重检查锁定、静态只读方法、锁定方法),但当
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
由于 .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.
这实际上是线程安全的代码,因为您(间接)使用静态构造函数来创建实例(并且 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).