单例设计模式和多线程
生活随笔
收集整理的這篇文章主要介紹了
单例设计模式和多线程
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
單例設計模式
單例:整個項目中,有某個類或者某些特殊的類,屬于該類的對象只能建立一個。
#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;}/*...*/ };轉載于:https://www.cnblogs.com/xcantaloupe/p/10424985.html
總結
以上是生活随笔為你收集整理的单例设计模式和多线程的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 标准正弦波变频电源调制方式的实现
- 下一篇: mongodb如何根据字段(数组类型)的