Files
rtphone/src/engine/helper/HL_Singletone.h
2018-06-05 11:05:37 +03:00

39 lines
875 B
C++

#ifndef __HL_SINGLETONE_H
#define __HL_SINGLETONE_H
#include <atomic>
#include <mutex>
template <class T>
class SafeSingleton
{
protected:
static std::atomic<T*> SharedInstance;
static std::mutex mMutex;
public:
static T& instance()
{
T* tmp = SharedInstance.load(std::memory_order_relaxed);
std::atomic_thread_fence(std::memory_order_acquire);
if (tmp == nullptr)
{
std::lock_guard<std::mutex> lock(mMutex);
tmp = SharedInstance.load(std::memory_order_relaxed);
if (tmp == nullptr)
{
tmp = new T();
std::atomic_thread_fence(std::memory_order_release);
SharedInstance.store(tmp, std::memory_order_relaxed);
}
}
return *tmp;
}
};
template <class T>
std::atomic<T*> SafeSingleton<T>::SharedInstance;
template <class T>
std::mutex SafeSingleton<T>::mMutex;
#endif