You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
54 lines
948 B
C++
54 lines
948 B
C++
#ifndef _H_LPSINGLETON_H_
|
|
#define _H_LPSINGLETON_H_
|
|
|
|
#include <mutex>
|
|
#include <atomic>
|
|
|
|
template<class T>
|
|
class lpsingleton
|
|
{
|
|
public:
|
|
static T* instance()
|
|
{
|
|
T *sin = s_this.load(std::memory_order_acquire);
|
|
|
|
if (!sin) {
|
|
std::lock_guard<std::mutex> locker(s_mutex);
|
|
sin = s_this.load(std::memory_order_relaxed);
|
|
if (!sin) {
|
|
sin = new T;
|
|
s_this.store(sin, std::memory_order_release);
|
|
}
|
|
}
|
|
|
|
return sin;
|
|
}
|
|
|
|
static void uninstance()
|
|
{
|
|
T *sin = s_this.load(std::memory_order_relaxed);
|
|
if (sin) {
|
|
std::lock_guard<std::mutex> locker(s_mutex);
|
|
delete sin;
|
|
sin = nullptr;
|
|
}
|
|
}
|
|
|
|
protected:
|
|
lpsingleton() = default;
|
|
virtual ~lpsingleton() = default;
|
|
private:
|
|
lpsingleton(const T&) = delete;
|
|
T& operator=(const T&) = delete;
|
|
|
|
static std::atomic<T*> s_this;
|
|
static std::mutex s_mutex;
|
|
};
|
|
|
|
template<class T>
|
|
std::atomic<T*> lpsingleton<T>::s_this;
|
|
|
|
template<class T>
|
|
std::mutex lpsingleton<T>::s_mutex;
|
|
|
|
#endif |