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.
whellvalue/src/tpMain/lp_singleton.h

56 lines
1.1 KiB
C

5 years ago
#ifndef LP_SINGLETON_H
#define LP_SINGLETON_H
#include <mutex>
#include <atomic>
template<class T>
class lp_singleton
{
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() = default;
virtual ~lp_singleton() = default;
private:
lp_singleton(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<T>::s_this;
template<class T>
std::mutex lp_singleton<T>::s_mutex;
#endif // LP_SINGLETON_H