C++的单例模式【饱汉式】【使用atexit + pthread_once】【线程安全】

写这个单例模式的要点:

头文件:<stdlib.h> <iostream>

① 两个静态成员变量:Singeleton* pInstance、pthread_once_t once

② 初始化 pInstance = nullptr;once = PTHREAD_ONCE_INIT

③ 在静态成员函数中注册pthread_once(&once,init_r)

④ 在init_r中注册销毁单例对象的函数,atexit(destory),并将pInstance  = new Singeleton()

⑤ 将构造函数和析构函数私有化;将拷贝构造和赋值运算符函数delete

#include <iostream>
#include <stdlib.h>

using namespace std;
class Singeleton
{
public:
    static Singeleton* getInstance()
    {
        pthread_once(&once,init_r);
        return pInstance;
    }

    void init(int ix,int iy)
    {
        this->ix = ix;
        this->iy = iy;
    }

    void myPrint()
    {
        cout << "ix:" << ix << ",iy:" << iy << "\n";
    }

private:
    static void init_r()
    {
        atexit(destory);
        pInstance = new Singeleton();
    }

    static void destory()
    {
        delete pInstance;
    }

    ~Singeleton() = default;
    Singeleton() = default;
    Singeleton& operator=(const Singeleton&) = delete;
    Singeleton(const Singeleton&) = delete;
private:
    int ix;
    int iy;
    static Singeleton* pInstance;
    static pthread_once_t once;
};
Singeleton* Singeleton::pInstance = nullptr;
pthread_once_t Singeleton::once = PTHREAD_ONCE_INIT;

int main(int argc, char const *argv[])
{
    Singeleton* p1 = Singeleton::getInstance();
    Singeleton* p2 = Singeleton::getInstance();

    cout << p1 << "\n";
    cout << p2 << "\n";

    p1->init(2,5);
    p1->myPrint();
    return 0;
}

注:pthread_once在程序中只会执行一次,并且在执行的时候会调用静态的init_r,这个函数对单例对象进行了初始化,并且注册了atexit的destory函数,保证了单例对象的资源被释放

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值