您的位置:首页 > 编程语言 > C语言/C++

利用c++11实现线程安全的单例类

2018-03-05 16:39 274 查看
工作中单例类比较常见,主要是为了防止频繁地创建和销毁某个对象。下文是利用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?
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: