zoukankan      html  css  js  c++  java
  • 考虑线程安全但效率不高的单例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;
    }
  • 相关阅读:
    模版的完全特化与偏特化
    [转]windows消息机制(MFC)
    MFC宏常识
    半透明AlphaBlend
    new、operator new、placement new
    DuplicateHandle
    Mac OS X 更新JAMF域控配置
    生成自签名CA+SSL证书
    Office 2016系列下载地址
    Spring Security静态资源访问
  • 原文地址:https://www.cnblogs.com/lihaozy/p/2781599.html
Copyright © 2011-2022 走看看