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.
51 lines
937 B
C
51 lines
937 B
C
|
4 years ago
|
#pragma once
|
||
|
|
|
||
|
|
#include <mutex>
|
||
|
|
#include <atomic>
|
||
|
|
|
||
|
|
template<class T>
|
||
|
|
class lp_singleton_base
|
||
|
|
{
|
||
|
|
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:
|
||
|
|
lp_singleton_base() = default;
|
||
|
|
virtual ~lp_singleton_base() = default;
|
||
|
|
private:
|
||
|
|
lp_singleton_base(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*> lp_singleton_base<T>::s_this;
|
||
|
|
|
||
|
|
template<class T>
|
||
|
|
std::mutex lp_singleton_base<T>::s_mutex;
|