多线程中的单例模式-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();

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值