多线程安全的单例模式(使用判断nullptr和call_once两种方法)

转载请注明: https://blog.csdn.net/Stephen___Qin/article/details/115583694ios

使用判断nullptr

#include <thread>
#include <iostream>
using namespace std;

class Singleton
{
private:
    Singleton()
    {
    }
    
    static Singleton * m_singleton;//C++类中不能够定义本身类的对象,可是能够定义本身类的指针和引用.
    
public:
    static Singleton * getInstance();
};

Singleton * Singleton::m_singleton = nullptr;
Singleton * Singleton::getInstance()
{
    if(m_singleton == nullptr)
        m_singleton = new Singleton();
    
    return m_singleton;
}

void ThreadFunc()
{
    Singleton *s = Singleton::getInstance();
    std::cout << "s:" << s << std::endl;
}

int main()
{
    thread t1(ThreadFunc);
    t1.join();

    thread t2(ThreadFunc);
    t2.join();

    thread t3(ThreadFunc);
    t3.join();

    return 0;
}

注意:
1.构造函数要定义为private,这样就没法建立对象,保证只能经过类名来访问单例.
2.static变量须要在类外初始化.为何呢?由于静态变量不属于某个对象,而是属于类,若是放在类内初始化,则变成了这个对象的了,这就和以前的假设矛盾了函数

使用call_once

#include <thread>
#include <iostream>
#include <mutex>	
using namespace std;

static std::once_flag of;

class Singleton
{
private:
    Singleton()
    {
    }
    
    static Singleton * m_singleton;
    
public:
    static Singleton * getInstance();
};

Singleton * Singleton::m_singleton = nullptr;

Singleton * Singleton::getInstance()
{
    std::call_once(of, []()
    {
        m_singleton = new Singleton();    
    }
    );

    return m_singleton;
}

void ThreadFunc()
{
    Singleton *s = Singleton::getInstance();
    std::cout << "s:" << s << std::endl;
}

int main()
{
    thread t1(ThreadFunc);
    t1.join();

    thread t2(ThreadFunc);
    t2.join();

    thread t3(ThreadFunc);
    t3.join();

    return 0;
}

注意:
1.call_once和once_flag的头文件是<mutex>
2.once_flag定义为static或者全局对象,不然不一样线程间不可见,则没法起到做用.spa

参考文章:
https://zhuanlan.zhihu.com/p/71900518.net

相关文章
相关标签/搜索