c++單例模式[2]--Meyers方式--多執行緒單例
阿新 • • 發佈:2018-12-14
[1]單例模式中最大的缺陷就是執行緒安全與判斷的開銷
#pragma once #include <iostream> #include <thread> using namespace std; /** *Meyers 方案(利用語言級別的靜態成員屬性來實現) * 1優化了 判斷消耗, * 2優化了釋放例項,不會導致記憶體洩露 * 3多執行緒下保證一個例項(但是並不是真正意義的執行緒安全實現) *Date :[10/9/2018 ] *Author :[RS] */ class Singleton2 { private: Singleton2() { cout << "begin" << endl; this_thread::sleep_for(chrono::seconds(1)); mCount = 10; cout << "end" << endl; } ~Singleton2() { cout << "析構" << endl; } public: //單例物件使用區域性靜態變數的方法,從而延遲到呼叫時例項化 static Singleton2& GetInstance() { static Singleton2 instacne; return instacne; } public: void Print() { cout << this_thread::get_id() <<":count:" << mCount << endl; } private: Singleton2(const Singleton2&) = delete; Singleton2* operator=(const Singleton2&) = delete; private: int mCount; };
主程式
#include "Singleton2.hpp"
void fun() {
Singleton2::GetInstance().Print();
}
void main() {
cout.sync_with_stdio(true);
thread t(fun);
thread t2(fun);
thread t3(fun);
t.join();
t2.join();
t3.join();
system("pause");
}