【c++】【多線程】單例模式及其性能 原

併發場景下的單例模式,需要加鎖。

#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;
}

二者性能測試代碼如下:

#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");

}

測試結果如下:

方式一結果:

方式二結果:

可見:運行時間爲32倍的差距。在性能要求較高的場景下,最小粒度實現的方式,明顯性能更好。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章