当前位置:   article > 正文

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

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;
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

以下是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;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/245749
推荐阅读
相关标签
  

闽ICP备14008679号