[C++] 实现线程安全的懒汉单例模式

线程安全的懒汉单例模式

利用unique_lock互斥锁实现,lock_guard亦可。

两种锁的优劣

std::unique_lock 与std::lock_guard都能实现自动加锁与解锁功能,但是std::unique_lock要比std::lock_guard更灵活,但是更灵活的代价是占用空间相对更大一点且相对更慢一点。

代码实现

废话不多说直接上代码
以下是头文件内容

public:
	~Singleton();
	static Singleton* GetInstance();
	static void DestoryInstance();
private:
	Singleton();
	static Singleton* m_Singleton;
	static std::mutex m_mutex;

以下是CPP内容

Singleton* Singleton::m_Singleton;
std::mutex Singleton::m_mutex;
Singleton::Singleton()
{
}
Singleton::~Singleton()
{
}

Singleton* Singleton::GetInstance()
{
	if (m_Singleton == nullptr)
	{
		std::unique_lock<std::mutex> lock(m_mutex);
		if (m_Singleton == nullptr)
		{
			m_Singleton = new Singleton();
		}
	}
	return m_Singleton;
}

void Singleton::DestoryInstance()
{
	delete m_Singleton;
	m_Singleton = nullptr;
}

猜你喜欢

转载自blog.csdn.net/m0_38125278/article/details/85611637