我有以下课程
class Singleton
{
private:
static Singleton *p_inst;
Singleton();
public:
static Singleton * instance()
{
if (!p_inst)
{
p_inst = new Singleton();
}
return p_inst;
}
};
请详细说明在多线程环境下实现Singleton时的注意事项。
在多线程中该子句
if(!p_inst)
{
p_inst = new Singleton();
}
实际上是3个独立的动作。你得到的价值是p_inst
,设置值p_inst
并写出值p_inst
。所以 get-set-write 意味着你需要加锁p_inst
否则你可以有 2 个线程来创建一个Singleton
每个线程使用的值。
以下是您查看问题的方式,假设您的Singleton
有一个可变字段val
:
thread A -> p_inst is NULL
thread B -> p_inst is NULL
thread A -> set to Singleton (1)
thread B -> set to Singleton (2)
thread C -> p_inst is Singleton (2)
thread A -> set val to 4
thread B -> set val to 6
thread C -> get val (it's 6)
thread A -> get val (it's 4!!)
你看?有 2 个 Singleton 副本在浮动,其中两个副本都不知道另一个副本。第三个线程检查Singleton
只会看到最后一个作业。但通过锁定,您可以防止多重分配和此类问题。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)