74 lines
1.7 KiB
C++
74 lines
1.7 KiB
C++
#pragma once
|
|
/**
|
|
* @file SingletonTemp.hpp
|
|
* @brief 单例模式 模板类 加锁
|
|
* @author your name (you@domain.com)
|
|
* @version 0.1
|
|
* @date 2023-12-22
|
|
*
|
|
* Copyright: Baosight Co. Ltd.
|
|
* DO NOT COPY/USE WITHOUT PERMISSION
|
|
*
|
|
*/
|
|
#include <iostream>
|
|
#include <mutex>
|
|
|
|
// namespace {
|
|
// std::mutex local_mutex;
|
|
// }
|
|
template <class T> class SingletonTemp {
|
|
private:
|
|
static std::mutex &get_mutex() {
|
|
static std::mutex instance_mutex; // 每个类型有自己的静态mutex
|
|
return instance_mutex;
|
|
}
|
|
|
|
protected:
|
|
SingletonTemp();
|
|
|
|
public:
|
|
virtual ~SingletonTemp(void);
|
|
|
|
static T *GetInstancePtr();
|
|
static T &GetInstance();
|
|
static bool release(void);
|
|
|
|
private:
|
|
static T *mp_singleton;
|
|
};
|
|
|
|
template <class T> T *SingletonTemp<T>::mp_singleton = nullptr;
|
|
|
|
template <class T> SingletonTemp<T>::SingletonTemp(void) {}
|
|
|
|
template <class T> SingletonTemp<T>::~SingletonTemp(void) { release(); }
|
|
|
|
template <class T> T *SingletonTemp<T>::GetInstancePtr() {
|
|
// std::lock_guard<std::mutex> guard(local_mutex);
|
|
std::lock_guard<std::mutex> guard(get_mutex()); // 使用类型特定的锁
|
|
if (mp_singleton == nullptr) {
|
|
mp_singleton = new T();
|
|
}
|
|
return mp_singleton;
|
|
}
|
|
|
|
template <class T> T &SingletonTemp<T>::GetInstance() {
|
|
// std::lock_guard<std::mutex> guard(local_mutex);
|
|
std::lock_guard<std::mutex> guard(get_mutex()); // 使用类型特定的锁
|
|
if (mp_singleton == nullptr) {
|
|
mp_singleton = new T();
|
|
}
|
|
return *mp_singleton;
|
|
}
|
|
|
|
template <class T> bool SingletonTemp<T>::release(void) {
|
|
// std::lock_guard<std::mutex> guard(local_mutex);
|
|
std::lock_guard<std::mutex> guard(get_mutex()); // 使用类型特定的锁
|
|
bool rtc = true;
|
|
if (mp_singleton != nullptr) {
|
|
delete mp_singleton;
|
|
mp_singleton = nullptr;
|
|
}
|
|
return rtc;
|
|
}
|