c++ /QT 加锁的懒汉式单例

c++ 加锁的懒汉式单例

singleton.h

#ifndef SHAREPTR_T_H
#define SHAREPTR_T_H

#pragma once
#include 
#include 

template<typename T>
class SingletonT
{
public:
    //GetInstance
    template<typename ...Args>
    static std::shared_ptr<T> GetInstance(Args&&... args) {
        if (!sington_) {
            std::lock_guard<std::mutex> lock(mutex_);
            if (nullptr == sington_) {
                sington_ = std::make_shared<T>(std::forward<Args>(args)...);
            }
        }
        return sington_;
    }

    //DelInstance
    static void DelInstance() {
        std::lock_guard<std::mutex> lock(mutex_);
        if (sington_) {
            sington_.reset();
            sington_ = nullptr;
        }
    }

private:
    SingletonT() = default;
    SingletonT(const SingletonT&) = delete;
    SingletonT& operator=(const SingletonT&) = delete;
    ~SingletonT() = default;

private:
    static std::shared_ptr<T> sington_;
    static std::mutex mutex_;
};

template<typename T>
std::shared_ptr<T> SingletonT<T>::sington_ = nullptr;

template<typename T>
std::mutex SingletonT<T>::mutex_;


#endif // SHAREPTR_T_H

QT 方式

devmanager.h

#ifndef DEVMANAGER_H
#define DEVMANAGER_H

#include 
#include 
#include 


/*!
 * \brief The DevManager class 设备管理单例,多线程支持
 */
class DevManager : public QObject
{
    Q_OBJECT
public:
    static QSharedPointer<DevManager> getInstance();
    ~DevManager();
signals:

private:
    //私有,构造
    DevManager();
    //禁止,拷贝构造
    DevManager(const DevManager &other)=delete;
    //禁止,赋值构造
    const DevManager &operator=(const DevManager &other)=delete;

private:
    static QSharedPointer<DevManager> m_sington;
    static QMutex m_mutex;
};

#endif // DEVMANAGER_H

devmanager.cpp

#include "devmanager.h"
#include
#include 


QSharedPointer<DevManager> DevManager::m_sington = nullptr;
QMutex DevManager::m_mutex;

static void doDeleteLater(DevManager *obj)
{
    obj->deleteLater();
    qDebug()<<Q_FUNC_INFO<<QThread::currentThreadId();
}

QSharedPointer<DevManager> DevManager::getInstance()
{
    if (m_sington.isNull()) {
        m_mutex.lock();
        if (m_sington.isNull()) {
            m_sington = QSharedPointer<DevManager>(new DevManager, doDeleteLater);
        }
        m_mutex.unlock();
    }
    return m_sington;
}

DevManager::~DevManager()
{
    qDebug()<<Q_FUNC_INFO<<QThread::currentThreadId();
}


DevManager::DevManager() : QObject(nullptr)
{
    qDebug()<<Q_FUNC_INFO<<QThread::currentThreadId();
}



你可能感兴趣的:(c++,QT/QML,c++,qt)