zoukankan      html  css  js  c++  java
  • 单例设计模式和多线程

    单例设计模式

    单例:整个项目中,有某个类或者某些特殊的类,属于该类的对象只能建立一个。

    #include<iostream>
    using namespace std;
    
    class MyCAS
    {
    private:
    	MyCAS(){}
    
    private:
    	static MyCAS *m_instance;
    
    public:
    	static MyCAS *GetInstance()   ///得到对象的接口函数
    	{
    		if(m_instance==NULL)
    		{
    			m_instance = new MyCAS();
    			static CGarhuishou cl;
    		}
    		return m_instance;
    	}
    
    	void func()
    	{
    		cout << "test" << endl;
    	}
    
    	class CGarhuishou  ///类中套类,释放对象
    	{
        public:
            ~CGarhuishou()
            {
                if(m_instance!=NULL)
                {
                    delete MyCAS::m_instance;
                    MyCAS::m_instance = NULL;
                }
            }
    	};
    };
    MyCAS *MyCAS::m_instance = NULL;
    
    int main()
    {
    	MyCAS *p_a = MyCAS::GetInstance();
    	p_a->func();
    	return 0;
    }
    
    

    单例设计模式共享数据问题分析、解决

    问题:需要在多个线程中创建单例类的对象,获得对象的接口函数GetInstance()要互斥,否则会导致m_instance = new MyCAS()执行多次。

    static MyCAS *GetInstance()   ///得到对象的接口函数
        {
            if(m_instance==NULL)   //提高效率,防止在创建对象后还需要一直加锁。
            {
                std::unique_lock<std::mutex>mymutex(resource_mutex);
                if(m_instance==NULL)
                {
                    m_instance = new MyCAS();
                    static CGarhuishou cl;
                }
            }
            return m_instance;
        }
    

    std::call_one();

    call_one功能:保证函数只执行一次

    std::once_flag g_flag;  ///系统定义的标记;
    class MyCAS
    {
        /*
        ...
        */
        static void CreateInstance()   ///只需要执行一次的部分
        {
            m_instance = new MyCAS();
            static CGarhuishou cl;
        }
        
        static MyCAS *GetInstance()   ///得到对象的接口函数
        {
            call_once(g_flag,CreateInstance);   ///第一个参数是个标记,第二个参数是只要执行的函数
            return m_instance;
        }
        /*
        ...
        */
    };
    
  • 相关阅读:
    各种redis的介绍:ServiceStack.Redis,StackExchange.Redis,CSRedis
    nginx 配置web服务
    安装Office Online Server
    买房哪些事?
    微服务演变:微服务架构介绍
    VUE 前端调用Base64加密,后端c#调用Base64解密
    程序员35岁前必须做完的事
    Vue 开发流程
    小程序快速认证
    vue页面打印成pdf
  • 原文地址:https://www.cnblogs.com/xcantaloupe/p/10424985.html
Copyright © 2011-2022 走看看