C++11单例设计模式(双检查锁)
- 2020 年 2 月 15 日
- 笔记
单例设计模式就是一个类只能实例化出一个对象,不能实例化出多个对象,单例模式分为两种,一种是饿汉单例模式,是指在类创建的时候就已经实例化出了一个对象,好处是这个模式没有线程安全问题,坏处是浪费资源,不管之后有没有用到,都会先实例化一个对象,代码如下:
std::mutex mlock; class Solution { private: Solution() {} static Solution* ptr; public: static Solution* Create() { return ptr; } }; Solution* Solution::ptr = new Solution();
还有一种是懒汉模式,顾名思义,当你需要用它的时候才去实例化对象,如果多个线程同时去实例化对象,那么产生的对象可能不唯一,所以存在线程安全的问题,避免这个线程安全的解决办法是用双检查锁(double checked locking),不是很难理解,具体实现过程就不在讲解,直接看代码吧:
#include <iostream> #include <mutex> std::mutex mlock; class Solution { public: static Solution* Create() { if (ptr == NULL) { std::unique_lock<std::mutex> MyUniqueLock(mlock); if (ptr == NULL) { ptr = new Solution(); static Destructor s; } } return ptr; } class Destructor { public: ~Destructor() { if (Solution::ptr != NULL) { delete Solution::ptr; Solution::ptr = NULL; } } }; private: static Solution* ptr; Solution() {}; }; Solution *(Solution::ptr) = NULL; void Thread() { Solution* tmp = Solution::Create(); std::cout << "My Thread Function" << std::endl; } int main() { std::thread t1(Thread); std::thread t2(Thread); t1.join(); t2.join(); return 0; }