#include "stdafx.h"
#include <atomic>
#include <mutex>
template<typename T>
class CSingleton_T
{
public:
static T &Instance()
{
T *tmp = m_pInstance.load(std::memory_order_acquire);
if (tmp == nullptr)
{
std::lock_guard<std::mutex> lock(m_instanceMutex);
if (tmp == nullptr)
{
static T temp;
tmp = &temp;
m_pInstance.store(tmp, std::memory_order_release);
}
}
return *tmp;
}
private:
static std::atomic<T *> m_pInstance;
static std::mutex m_instanceMutex; // 注意: xp系统上报错(原因:C++11的mutex和thread不支持xp)
};
template<typename T> std::atomic<T *> CSingleton_T<T>::m_pInstance;
template<typename T> std::mutex CSingleton_T<T>::m_instanceMutex;
#define SINGLETON(T) CSingleton_T<T>::Instance()
class A : public CSingleton_T<A>
{
public:
int Test()
{
int i = 0;
i++;
return i;
}
};
int main()
{
int ccc = SINGLETON(A).Test();
return 0;
}
单例模式实现(双锁)
最新推荐文章于 2024-08-23 02:08:39 发布