使用設(shè)計(jì)模式中的單例模式來實(shí)現(xiàn)C++的boost庫(kù)
線程安全的單例模式
一、懶漢模式:即第一次調(diào)用該類實(shí)例的時(shí)候才產(chǎn)生一個(gè)新的該類實(shí)例,并在以后僅返回此實(shí)例。
需要用鎖,來保證其線程安全性:原因:多個(gè)線程可能進(jìn)入判斷是否已經(jīng)存在實(shí)例的if語(yǔ)句,從而non thread safety。
使用double-check來保證thread safety。但是如果處理大量數(shù)據(jù)時(shí),該鎖才成為嚴(yán)重的性能瓶頸。
1、靜態(tài)成員實(shí)例的懶漢模式:
class Singleton
{
private:
static Singleton* m_instance;
Singleton(){}
public:
static Singleton* getInstance();
};
Singleton* Singleton::getInstance()
{
if(NULL == m_instance)
{
Lock();
//借用其它類來實(shí)現(xiàn),如boost
if(NULL == m_instance)
{
m_instance = new Singleton;
}
UnLock();
}
return m_instance;
}
2、內(nèi)部靜態(tài)實(shí)例的懶漢模式
這里需要注意的是,C++0X以后,要求編譯器保證內(nèi)部靜態(tài)變量的線程安全性,可以不加鎖。但C++ 0X以前,仍需要加鎖。
class SingletonInside
{
private:
SingletonInside(){}
public:
static SingletonInside* getInstance()
{
Lock();
// not needed after C++0x
static SingletonInside instance;
UnLock();
// not needed after C++0x
return instance;
}
};
二、餓漢模式:即無論是否調(diào)用該類的實(shí)例,在程序開始時(shí)就會(huì)產(chǎn)生一個(gè)該類的實(shí)例,并在以后僅返回此實(shí)例。
由靜態(tài)初始化實(shí)例保證其線程安全性,WHY?因?yàn)殪o態(tài)實(shí)例初始化在程序開始時(shí)進(jìn)入主函數(shù)之前就由主線程以單線程方式完成了初始化,不必?fù)?dān)心多線程問題。
故在性能需求較高時(shí),應(yīng)使用這種模式,避免頻繁的鎖爭(zhēng)奪。
class SingletonStatic
{
private:
static const SingletonStatic* m_instance;
SingletonStatic(){}
public:
static const SingletonStatic* getInstance()
{
return m_instance;
}
};
//外部初始化 before invoke main
const SingletonStatic* SingletonStatic::m_instance = new SingletonStatic;
boost庫(kù)的實(shí)現(xiàn)示例
單例本來是個(gè)很簡(jiǎn)單的模式,實(shí)現(xiàn)上應(yīng)該也是很簡(jiǎn)單,但C++單例的簡(jiǎn)單實(shí)現(xiàn)會(huì)有一些坑,有了上面線程安全的基礎(chǔ),下面來看看為了避免這些坑怎樣一步步演化到boost庫(kù)的實(shí)現(xiàn)方式。
方案一
class QMManager
{
public:
static QMManager &instance()
{
static QMManager instance_;
return instance_;
}
}
這是最簡(jiǎn)單的版本,在單線程下(或者是C++0X下)是沒任何問題的,但在多線程下就不行了,因?yàn)閟tatic QMManager instance_;這句話不是線程安全的。
在局部作用域下的靜態(tài)變量在編譯時(shí),編譯器會(huì)創(chuàng)建一個(gè)附加變量標(biāo)識(shí)靜態(tài)變量是否被初始化,會(huì)被編譯器變成像下面這樣(偽代碼):
static QMManager &instance()
{
static bool constructed = false;
static uninitialized QMManager instance_;
if (!constructed) {
constructed = true;
new(&s) QMManager; //construct it
}
return instance_;
}
這里有競(jìng)爭(zhēng)條件,兩個(gè)線程同時(shí)調(diào)用instance()時(shí),一個(gè)線程運(yùn)行到if語(yǔ)句進(jìn)入后還沒設(shè)constructed值,此時(shí)切換到另一線程,constructed值還是false,同樣進(jìn)入到if語(yǔ)句里初始化變量,兩個(gè)線程都執(zhí)行了這個(gè)單例類的初始化,就不再是單例了。
方案二
一個(gè)解決方法是加鎖:
static QMManager &instance()
{
Lock(); //鎖自己實(shí)現(xiàn)
static QMManager instance_;
UnLock();
return instance_;
}
但這樣每次調(diào)用instance()都要加鎖解鎖,代價(jià)略大。
方案三
那再改變一下,把內(nèi)部靜態(tài)實(shí)例變成類的靜態(tài)成員,在外部初始化,也就是在include了文件,main函數(shù)執(zhí)行前就初始化這個(gè)實(shí)例,就不會(huì)有線程重入問題了:
class QMManager
{
protected:
static QMManager instance_;
QMManager();
~QMManager(){};
public:
static QMManager *instance()
{
return &instance_;
}
void do_something();
};
QMManager QMManager::instance_; //外部初始化
這被稱為餓漢模式,程序一加載就初始化,不管有沒有調(diào)用到。
看似沒問題,但還是有坑,在一個(gè)2B情況下會(huì)有問題:在這個(gè)單例類的構(gòu)造函數(shù)里調(diào)用另一個(gè)單例類的方法可能會(huì)有問題。
看例子:
//.h
class QMManager
{
protected:
static QMManager instance_;
QMManager();
~QMManager(){};
public:
static QMManager *instance()
{
return &instance_;
}
};
class QMSqlite
{
protected:
static QMSqlite instance_;
QMSqlite();
~QMSqlite(){};
public:
static QMSqlite *instance()
{
return &instance_;
}
void do_something();
};
QMManager QMManager::instance_;
QMSqlite QMSqlite::instance_;
//.cpp
QMManager::QMManager()
{
printf("QMManager constructor\n");
QMSqlite::instance()->do_something();
}
QMSqlite::QMSqlite()
{
printf("QMSqlite constructor\n");
}
void QMSqlite::do_something()
{
printf("QMSqlite do_something\n");
}
這里QMManager的構(gòu)造函數(shù)調(diào)用了QMSqlite的instance函數(shù),但此時(shí)QMSqlite::instance_可能還沒有初始化。
這里的執(zhí)行流程:程序開始后,在執(zhí)行main前,執(zhí)行到QMManager QMManager::instance_;這句代碼,初始化QMManager里的instance_靜態(tài)變量,調(diào)用到QMManager的構(gòu)造函數(shù),在構(gòu)造函數(shù)里調(diào)用QMSqlite::instance(),取QMSqlite里的instance_靜態(tài)變量,但此時(shí)QMSqlite::instance_還沒初始化,問題就出現(xiàn)了。
那這里會(huì)crash嗎,測(cè)試結(jié)果是不會(huì),這應(yīng)該跟編譯器有關(guān),靜態(tài)數(shù)據(jù)區(qū)空間應(yīng)該是先被分配了,在調(diào)用QMManager構(gòu)造函數(shù)前,QMSqlite成員函數(shù)在內(nèi)存里已經(jīng)存在了,只是還未調(diào)到它的構(gòu)造函數(shù),所以輸出是這樣:
QMManager constructor QMSqlite do_something QMSqlite constructor
方案四
那這個(gè)問題怎么解決呢,單例對(duì)象作為靜態(tài)局部變量有線程安全問題,作為類靜態(tài)全局變量在一開始初始化,有以上2B問題,那結(jié)合下上述兩種方式,可以解決這兩個(gè)問題。boost的實(shí)現(xiàn)方式是:?jiǎn)卫龑?duì)象作為靜態(tài)局部變量,但增加一個(gè)輔助類讓單例對(duì)象可以在一開始就初始化。如下:
//.h
class QMManager
{
protected:
struct object_creator
{
object_creator()
{
QMManager::instance();
}
inline void do_nothing() const {}
};
static object_creator create_object_;
QMManager();
~QMManager(){};
public:
static QMManager *instance()
{
static QMManager instance;
return &instance;
}
};
QMManager::object_creator QMManager::create_object_;
class QMSqlite
{
protected:
QMSqlite();
~QMSqlite(){};
struct object_creator
{
object_creator()
{
QMSqlite::instance();
}
inline void do_nothing() const {}
};
static object_creator create_object_;
public:
static QMSqlite *instance()
{
static QMSqlite instance;
return &instance;
}
void do_something();
};
QMManager::object_creator QMManager::create_object_;
QMSqlite::object_creator QMSqlite::create_object_;
結(jié)合方案3的.cpp,這下可以看到正確的輸出和調(diào)用了:
QMManager constructor QMSqlite constructor QMSqlite do_something
來看看這里的執(zhí)行流程:
初始化QMManager類全局靜態(tài)變量create_object_
->調(diào)用object_creator的構(gòu)造函數(shù)
->調(diào)用QMManager::instance()方法初始化單例
->執(zhí)行QMManager的構(gòu)造函數(shù)
->調(diào)用QMSqlite::instance()
->初始化局部靜態(tài)變量QMSqlite instance
->執(zhí)行QMSqlite的構(gòu)造函數(shù),然后返回這個(gè)單例。
跟方案三的區(qū)別在于QMManager調(diào)用QMSqlite單例時(shí),方案3是取到全局靜態(tài)變量,此時(shí)這個(gè)變量未初始化,而方案四的單例是靜態(tài)局部變量,此時(shí)調(diào)用會(huì)初始化。
跟最初方案一的區(qū)別是在main函數(shù)前就初始化了單例,不會(huì)有線程安全問題。
最終boost
上面為了說明清楚點(diǎn)去除了模版,實(shí)際使用是用模版,不用寫那么多重復(fù)代碼,這是boost庫(kù)的模板實(shí)現(xiàn):
template <typename T>
struct Singleton
{
struct object_creator
{
object_creator(){ Singleton<T>::instance(); }
inline void do_nothing()const {}
};
static object_creator create_object;
public:
typedef T object_type;
static object_type& instance()
{
static object_type obj;
//據(jù)說這個(gè)do_nothing是確保create_object構(gòu)造函數(shù)被調(diào)用
//這跟模板的編譯有關(guān)
create_object.do_nothing();
return obj;
}
};
template <typename T> typename Singleton<T>::object_creator Singleton<T>::create_object;
class QMManager
{
protected:
QMManager();
~QMManager(){};
friend class Singleton<QMManager>;
public:
void do_something(){};
};
int main()
{
Singleton<QMManager>::instance()->do_something();
return 0;
}
其實(shí)Boost庫(kù)這樣的實(shí)現(xiàn)像打了幾個(gè)補(bǔ)丁,用了一些特殊技巧,雖然確實(shí)繞過了坑實(shí)現(xiàn)了需求,但感覺挺不好的。
相關(guān)文章
基于VC中使用ForceInclude來強(qiáng)制包含stdafx.h的解決方法
本篇文章是對(duì)VC中使用ForceInclude來強(qiáng)制包含stdafx.h的解決方法進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-05-05
c語(yǔ)言讀取obj文件轉(zhuǎn)換數(shù)據(jù)的小例子
c語(yǔ)言讀取obj文件轉(zhuǎn)換數(shù)據(jù)的小例子,需要的朋友可以參考一下2013-03-03
重構(gòu)-C++實(shí)現(xiàn)矩陣的簡(jiǎn)單實(shí)例
下面小編就為大家?guī)硪黄貥?gòu)-C++實(shí)現(xiàn)矩陣的簡(jiǎn)單實(shí)例。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2016-06-06
C++模板基礎(chǔ)之函數(shù)模板與類模板實(shí)例詳解
C++ 除了支持函數(shù)模板,還支持類模板(Class Template),所以下面這篇文章主要給大家介紹了關(guān)于C++模板基礎(chǔ)之函數(shù)模板與類模板的相關(guān)資料,需要的朋友可以參考下2021-06-06
C語(yǔ)言實(shí)現(xiàn)快速排序算法實(shí)例
快速排序時(shí)間復(fù)雜度為O(nlogn),是數(shù)組相關(guān)的題目當(dāng)中經(jīng)常會(huì)用到的算法,下面這篇文章主要給大家介紹了關(guān)于C語(yǔ)言實(shí)現(xiàn)快速排序算法的相關(guān)資料,需要的朋友可以參考下2022-06-06

