併發場景下的單例模式,須要加鎖。ios
#pragma once #include <mutex> using namespace std; class SingleInstance { public: static SingleInstance *getInstance(); private: SingleInstance() = default; ~ SingleInstance() = default; private: static SingleInstance * instance; static mutex instanceLock; };
一:簡單粗暴的方式併發
#include "SingleInstance.h" SingleInstance * SingleInstance::instance = nullptr; mutex SingleInstance::instanceLock; SingleInstance *SingleInstance::getInstance() { lock_guard<mutex> lk(instanceLock); if (instance == nullptr) { instance = new SingleInstance(); } return instance; }
入口處直接加鎖,其實這樣加鎖,鎖粒度有點大性能
二:最小粒度加鎖測試
SingleInstance *SingleInstance::getInstance(){ if (instance == nullptr) { lock_guard<mutex> lk(instanceLock); if (instance == nullptr) { instance = new SingleInstance(); } } return instance; }
兩者性能測試代碼以下:spa
#include <iostream> #include <string> #include <map> #include "LogTime.h" #include "SingleInstance.h" using namespace std; int main(int argc, int * argv[]) { LogTime time; time.Start(); for (int i = 0; i < 1e5; i++) { // 獲取單例1萬次 SingleInstance::getInstance(); } time.End(); cout << "run:" << time.GetRunTime() << endl; system("pause"); }
測試結果以下:code
方式一結果:blog
方式二結果:get
可見:運行時間爲32倍的差距。在性能要求較高的場景下,最小粒度實現的方式,明顯性能更好。string