C++ 设计者模式——单例模式
单例用到锁的定义实现:mutex.h#pragma once#include<windows.h>#include<iostream>using namespace std;class IMyLock{public:virtual ~IMyLock() {}virtual void Lock() const = 0;virtual void...
·
单例用到锁的定义实现:
mutex.h
#pragma once
#include<windows.h>
#include<iostream>
using namespace std;
class IMyLock
{
public:
virtual ~IMyLock() {}
virtual void Lock() const = 0;
virtual void UnLock() const = 0;
};
class Mutex:public IMyLock
{
public:
Mutex();
~Mutex();
virtual void Lock() const;
virtual void UnLock() const;
private:
HANDLE m_mutex;
};
class CLock
{
public:
CLock(const IMyLock&);
~CLock();
private:
const IMyLock& m_lock;
};
#include"mutex.h"
Mutex::Mutex()
{
m_mutex = ::CreateMutex(NULL, false, NULL);
}
Mutex::~Mutex()
{
::CloseHandle(m_mutex);
}
void Mutex::Lock()const
{
DWORD d = WaitForSingleObject(m_mutex, INFINITE);
}
void Mutex::UnLock()const
{
::ReleaseMutex(m_mutex);
}
CLock::CLock(const IMyLock& m) :m_lock(m)
{
m_lock.Lock();
}
CLock::~CLock()
{
m_lock.UnLock();
}
有三种方式实现单例:有单线程、和多线程安全的
#pragma once
#include<iostream>
#include"mutex.h"
using namespace std;
using std::_Atomic_counter_t;
class Singleton
{
public:
static Singleton* GetStance();
private:
Singleton()
{
}
Singleton(const Singleton& singleton)
{
}
private:
static Singleton* m_lpSingleton;
static IMyLock * mutex;
};
#include"Singleton.h"
Singleton* Singleton::m_lpSingleton = new Singleton();
IMyLock* Singleton::mutex = new Mutex();
//1-1第一种方式会浪费时间:第一次之后在获取实例,其实是不需要上锁的。
Singleton* Singleton::GetStance()
{
mutex->Lock();
if (m_lpSingleton == NULL)
return m_lpSingleton =new Singleton();
return m_lpSingleton;
mutex->UnLock();
}
//1-2 锁加在里面,判断俩次
//Singleton* Singleton::GetStance()
//{
// if (m_lpSingleton == NULL)
// {
// mutex->Lock();
// if(m_lpSingleton == NULL)
// return m_lpSingleton = new Singleton();
// mutex->UnLock();
// }
// return m_lpSingleton;
//}
// 1-3 在1-2版本中会存在如下问题:
/*
在new Singleton是先分配内存然后调用Singleton构造函数,然后将地址给m_lpSingleton,但是会出现意外
分配完内存之后就赋值给m_lpSingleton,然后在调用构造函数.此时获取的实例就不是真实的对象地址了。
*/
/*C++ 11版本之后的跨平台实现(volatile)
std::atomic<Singleton*>Singleton::m_instance;
std::mutex Singleton::m_mutex;
Singleton* Singleton::GetStance()
{
Singleton* tmp = m_instance.load(std::memory_order_relaxed);
std::atomic_thread_fence(std::memory_order_acquire);
if (tmp == nullptr)
{
std::lock_guard<std::mutex>lock(m_mutex);
tmp = m_instance.load(std::memory_order_relaxed);
if (tmp == nullptr)
{
tmp = new Singleton;
std::atomic_thread_fence(std::memory_order_release);
m_instance.store(tmp, std::memory_order_relaxed);
}
}
return tmp;
}
*/
更多推荐
已为社区贡献1条内容
所有评论(0)