考虑线程安全但效率不高的单例C++代码

本文的单例代码考虑了线程安全,但是由于每次Lock() UnLock()所花费的时间比较多,所以效率不高,代码如下:

#include <iostream>

using namespace std;

void Lock()
{
    //some mutex code
}

void UnLock()
{
    //some mutex code
}

class Singleton{
public:
    static Singleton* GetInstance()
    {
        Lock();
        if (m_Instance == NULL)                // 如果在这句话执行完毕后,线程发生时间片切换,那么就会发生每个线程都创建一个对象,
                                            // 并且最终只有一个对象由m_Instance指向,而其他对象由于没有指针指向而最终无法delete掉
                                            // 所以在上面进行了Lock()
        {
            m_Instance = new Singleton();
        }
        UnLock();
        return m_Instance;
    }

    static void DeleteInstance()
    {
        Lock();
        if (m_Instance)
        {
            delete m_Instance;
            m_Instance = NULL;
        }
        UnLock();
    }

    void TestPrint()
    {
        cout<<"lala"<<endl;
    }
private:
    static Singleton* m_Instance;

    Singleton(){}
    ~Singleton(){}
};

Singleton* Singleton::m_Instance = NULL;

int main()
{
    Singleton::GetInstance()->TestPrint();
    return 1;
}
原文地址:https://www.cnblogs.com/lihaozy/p/2781599.html