工作中单例类比较常见,主要是为了防止频繁地创建和销毁某个对象。下文是利用C++11的多线程库编写了一个线程安全的singleton类,类的描述为:
(1) 懒汉式单例类: 即使用的时候才创建;
(2) 加双重判断:第一个判断是为了防止频繁地加锁和解锁,第二个判断是为了保证实例只创建一次;
(3)利用unique_lock的局部特性,防止忘记解锁而导致死锁问题;
#include <thread>
#include <mutex>
#include <iostream>
class Singleton {
public:
static Singleton* get_instance() {
if (m_instance == nullptr) {
std::unique_lock<std::mutex> lck (m_mutex);
if (m_instance == nullptr) {
std::cout << "new Singleton called" << std::endl;
m_instance = new Singleton;
}
}
return m_instance;
}
void hello() {
std::cout << "hello, are you ok?" << std::endl;
}
private:
static std::mutex m_mutex;
static Singleton * m_instance;
Singleton(){};
~Singleton(){};
Singleton(const Singleton&){};
Singleton& operator = (const Singleton&);
};
Singleton* Singleton::m_instance = nullptr;
std::mutex Singleton::m_mutex;
void hello1() {
Singleton* pt = Singleton::get_instance();
pt->hello();
}
void hello2() {
Singleton* pt = Singleton::get_instance();
pt->hello();
}
int main(int argc, char* argv[]) {
Singleton* pt_s = Singleton::get_instance();
std::thread t1(hello1);
std::thread t2(hello2);
t1.join();
t2.join();
return 0;
}
输出如下:
new Singleton called
hello, are you ok?
hello, are you ok?
版权声明:本文为JXH_123原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。