Singleton模式的double check实现方式

T* pInstance = 0;

T* getInstance()
{
    if (pInstance == NULL)
    {
        lock();
        if (pInstance == NULL)
            pInstance = new T;
        unlock();
    }
    return pInstance;
}

如果两个线程同时发起

当为null时,其中一个线程创建示例,因为有同步的关系,另一个线程开始被阻塞,然后等示例创建完毕,
第二个线程又创建了一个新的示例;导致创建了2次。。。所以要判断2次。。。

原文地址:https://www.cnblogs.com/kex1n/p/2286464.html