//懶漢式 1
class CSingleton
{
private:
//構造 拷貝 賦值均是私有或關閉
CSingleton();
static pthread_t mutex_;
public:
CSingleton(const Singleton&)=delete;
CSingleton& operator=(const Singleton&)=delete;
static Singleton *Getinstance()
{
if(m_Instance == NULL)
{ //double check
pthread_mutex_lock(mutex_); //用lock實現線程安全
if(m_Instance == NULL)
{
m_Instance = new Singleton();
}
pthread_mutex_unlock(mutex_)
}
return m_Instance;
}
static Singleton *m_Instance;
};
Singleton* CSingleton::m_Instance = 0;
//懶漢式 2
class CSingleton
{
private:
CSingleton();
public:
CSingleton(const Singleton&)=delete;
CSingleton& operator=(const Singleton&)=delete;
static Singleton* get_instance(){
static Singleton* m_instance = new Singleton();
return instance;
}
};
//餓漢式
class CSingleton {
private:
CSingleton();
public:
CSingleton(const Singleton&)=delete;
CSingleton& operator=(const Singleton&)=delete;
static Singleton* m_instance = new Singleton();
Singleton* getInstance()
{
return m_instance;
}
}
三種常見的線程安全單例模式
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.