Qt实现线程安全的单例模式

实现方式

1、实现单例
把类的构造函数、拷贝构造函数、赋值操作符定义为private的;
把获取单例的接口和唯一的实例指针定义为static的,不需要实例化,直接通过类名即可访问。
2、支持多线程
采用双重校验法,在获取单例的函数中使用互斥锁,确保不会出现两个线程同时new出这个单例类的实例化。
3、解决内存泄漏
析构单例指针,单独写一个类,利用这个类的析构函数来析构单例指针。

代码实现

Instance.h

#ifndef INSTANCE_H
#define INSTANCE_H

#include <QObject>
#include <QMutex>
#include <QDebug>

class Instance : public QObject
{
    
    
    Q_OBJECT
public:
    static Instance *getInstance()
    {
    
    
        if(m_pInstance == NULL)
        {
    
    
            QMutexLocker mlocker(&m_mutex);
            if(m_pInstance == NULL)
            {
    
    
                m_pInstance = new Instance();
            }
        }
        return m_pInstance;
    }
    void debugStr();//对外接口,实现功能
    QString m_str;//对外接口,实现功能
private:
    explicit Instance(QObject *parent = 0);//构造函数
    Instance(const Instance &,QObject *parent = 0): QObject(parent) {
    
    }//拷贝构造函数
    Instance& operator =(const Instance&){
    
    return *this;}//赋值操作符重写
    static Instance* m_pInstance;//定义单例指针
    static QMutex m_mutex;//互斥锁

public:
    class Garbo     //专门用来析构m_pInstance指针的类
    {
    
    
    public:
        ~Garbo()
        {
    
    
            if(m_pInstance != NULL)
            {
    
    
                delete m_pInstance;
                m_pInstance = NULL;
                qDebug()<<"["<<__FILE__<<"]"<<__LINE__<<__FUNCTION__<<"m_pInstance 被析构";
            }
        }
    };
    static Garbo m_garbo;
};
#endif // INSTANCE_H

Instance.cpp

#include "instance.h"
#include <QDebug>

Instance* Instance::m_pInstance = NULL;
Instance::Garbo m_Garbo;
QMutex Instance::m_mutex;
void Instance::debugStr()
{
    
    
    qDebug()<<"["<<__FILE__<<"]"<<__LINE__<<__FUNCTION__<<"debugStr ";
}

Instance::Instance(QObject *parent) : QObject(parent)
{
    
    
    m_str = "hello World!";
}

调用单例

包含头文件,通过单例入口调用函数或变量。
#include “instance.h”
Instance::getInstance()->debugStr();
Instance::getInstance()->m_str;

猜你喜欢

转载自blog.csdn.net/weixin_40355471/article/details/110426528