看到Singleton,学过设计模式的都知道,就是单例模式,意思是保证程序在执行时某个变量只有一个实例。
class Singleton {
public:
static Singleton * getInstance() {}
private:
Singleton(): {}
~Singleton(): {}
static Singleton * instance;
}
Singleton * Singleton::instance = NULL;
Singleton * Singleton::getInstance(){
if(instance == NULL){
instance = new Singleton; //pos
}
return instance;
}
以上的代码只是对于单线程的,因为如果有多个线程调用getInstance,可能一个线程刚走到pos的位置,第二个线程在做if判断,那么它判断也会成立,因为此时instance并未赋值成功。
如果需要多进程实现,要应用到锁,类似进程pv操作,保证同一时间只有一个进程访问临界资源。所以getInstance()可以改成
Singleton * Singleton::instance(){
lock();
if(instance == NULL){
instance = new Singleton;
}
Unlock();
<pre name="code" class="cpp"> return instance;
}
上述代码通过锁来进行进程控制,可是使用锁的代价还是比较大的,而且如果instance != NULL的时候,这个锁是没有必要的,所以代码还可以在改一下。
Singleton * Singleton::instance(){
if(instance == NULL){
lock();
if(instance == NULL)
instance = new Singleton;
Unlock();
}<pre name="code" class="cpp"> return instance;
}
这样就可以减少花销了,也就是所谓的双检测。
不过这样也不一定是正确的,在查了资料之后,据大牛博客提到,编译器会自己优化而突破锁。还看到另一种解释是c++在new对象时,在c++11下可以使用关键字volatile来指定代码指向顺序,执行多线程处理。
static Singleton * volatile instance;
如果为了避免不必要的情况,还是在程序运行之前先实例下instance吧