多線程中的單例模式-C++

示例中使用模板創建單例對象,實際操作過程中換成具體類中實現。注意要求單例模式的類要把構造隱藏。 

#include <iostream>
#include <mutex>
using namespace std;
mutex g_single_mutex;
#define sync(action) g_single_mutex.lock(); action; g_single_mutex.unlock();
class testInstance
{
public:
	void print(int val)
	{
		cout << val << endl;
	}
};
template<class TTtype>
class SingleObjMode
{
public:
	static TTtype* instance();
	static mutex m_mutex;
protected:
	SingleObjMode() {}

	static TTtype* m_instance;
};

template<class TTtype>
TTtype* SingleObjMode<TTtype>::m_instance = nullptr;

template<class TTtype>
mutex SingleObjMode<TTtype>::m_mutex;

template<class TTtype>
TTtype* SingleObjMode<TTtype>::instance()
{
	if (m_instance == nullptr) // 避免每次進入函數都加鎖
	{
		m_mutex.lock();
		if (m_instance == nullptr)
		{
			TTtype* obj = new TTtype();
			cout << "create obj" << endl;
			m_instance = obj;
		}
		m_mutex.unlock();
	}
	return m_instance;
}

void singleModefunc(int val)
{
	testInstance *obj = SingleObjMode<testInstance>::instance();
	sync(obj->print(val))
}
void singleModeTest()
{
	vector<std::thread> vecThread;
	for (int i = 0; i < 100; ++i)
	{
		vecThread.push_back(std::thread(singleModefunc, i + 1));
	}
	for (int i = 0; i < vecThread.size(); ++i)
	{
		vecThread[i].join();
	}
}

int main()
{
    singleModeTest();
}
// 第二種線程安全單例模式
	class SingleInstance
	{
	public:
		static SingleInstance* instance()
		{
			return m_instance;
		}
		void doThing()
		{
			;
		}
	protected:
		SingleInstance() {}
		static SingleInstance* m_instance;
	};
	SingleInstance* SingleInstance::m_instance = new SingleInstance();

 

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