C++實(shí)現(xiàn)一個(gè)線程安全的單例工廠實(shí)現(xiàn)代碼
C++實(shí)現(xiàn)一個(gè)線程安全的單例工廠實(shí)現(xiàn)代碼
我們見到經(jīng)常有人用 static 局部對(duì)象的方式實(shí)現(xiàn)了類似單例模式,最近發(fā)現(xiàn)一篇文章明確寫明 編譯器在處理 static局部變量的時(shí)候 并不是線程安全的 ?。?!
http://blogs.msdn.com/b/oldnewthing/archive/2004/03/08/85901.aspx
于是實(shí)現(xiàn)了一個(gè)單例工廠 并且是線程安全的
#ifndef SINGLETONFACTORY_H
#define SINGLETONFACTORY_H
#include "windows.h"
#include <memory>
namespace Tools
{
template<class T>class SingletonFactory
{
public:
virtual ~SingletonFactory()
{
::DeleteCriticalSection(&__criticalSection);
}
std::auto_ptr<T>& GetInstance();
static SingletonFactory<T>* CreateSingletonFactory();
private:
SingletonFactory()
{
::InitializeCriticalSection(&__criticalSection);
}
std::auto_ptr<T> __singletonObj;
CRITICAL_SECTION __criticalSection;
};
//初始化創(chuàng)建 后續(xù)在多線程中使用
//還有另一種寫法是單獨(dú)的函數(shù)直接返回內(nèi)部單例包裝靜態(tài)成員在 多線程情況下不安全
//SingletonFactory::CreateSingletonFactory().GetInstance();
template<class T> SingletonFactory<T>* SingletonFactory<T>::CreateSingletonFactory(){
static SingletonFactory<T> temObj;
return &temObj;
}
//工廠實(shí)例
template<class T> std::auto_ptr<T>& SingletonFactory<T>::GetInstance()
{
if(__singletonObj.get()==0)
{
::EnterCriticalSection(&__criticalSection);
if(__singletonObj.get()==0)
__singletonObj=std::auto_ptr<T>(new T);
::LeaveCriticalSection(&__criticalSection);
}
return __singletonObj;
}
}
#endif // SINGLETONFACTORY_H
測(cè)試代碼
SingletonFactory<Data1>*singleton1=SingletonFactory<Data1>::CreateSingletonFactory(); singleton1->GetInstance()->x=100; cout<<singleton1->GetInstance()->x<<endl; singleton1->GetInstance()->y=200; cout<<singleton1->GetInstance()->x<<endl; cout<<singleton1->GetInstance()->y<<endl; SingletonFactory<Data2>*singleton2=SingletonFactory<Data2>::CreateSingletonFactory(); singleton2->GetInstance()->x=100; cout<<singleton2->GetInstance()->x<<endl; singleton2->GetInstance()->y=200; cout<<singleton2->GetInstance()->x<<endl; cout<<singleton2->GetInstance()->y<<endl;
感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!
相關(guān)文章
c語(yǔ)言實(shí)現(xiàn)詞頻統(tǒng)計(jì)的簡(jiǎn)單實(shí)例
下面小編就為大家?guī)?lái)一篇c語(yǔ)言實(shí)現(xiàn)詞頻統(tǒng)計(jì)的簡(jiǎn)單實(shí)例。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2016-09-09
C語(yǔ)言實(shí)現(xiàn)繪制南丁格爾玫瑰圖的示例代碼
玫瑰圖中有一種不等半徑的統(tǒng)計(jì)圖稱為南丁格爾玫瑰圖,網(wǎng)上很熱門,是一很有藝術(shù)感的漂亮的統(tǒng)計(jì)圖,下面我們就來(lái)看看如何使用C語(yǔ)言繪制它吧2024-03-03
C++使用cuBLAS加速矩陣乘法運(yùn)算的實(shí)現(xiàn)代碼
這篇文章主要介紹了C++使用cuBLAS加速矩陣乘法運(yùn)算,將cuBLAS庫(kù)的乘法運(yùn)算進(jìn)行了封裝,方便了算法調(diào)用,具體實(shí)現(xiàn)代碼跟隨小編一起看看吧2021-09-09
C語(yǔ)言實(shí)現(xiàn)第一次防死版掃雷游戲
大家好,本篇文章主要講的是C語(yǔ)言實(shí)現(xiàn)第一次防死版掃雷游戲,感興趣的同學(xué)趕快來(lái)看一看吧,對(duì)你有幫助的話記得收藏一下2022-01-01
C++11系列學(xué)習(xí)之可調(diào)用對(duì)象包裝器和綁定器
這篇文章主要介紹了C++11系列學(xué)習(xí)之可調(diào)用對(duì)象包裝器和綁定器,下文基于C++的相關(guān)資料展開詳細(xì)內(nèi)容介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考一下2022-04-04
C++實(shí)現(xiàn)通訊錄管理系統(tǒng)設(shè)計(jì)
這篇文章主要為大家詳細(xì)介紹了C++實(shí)現(xiàn)通訊錄管理系統(tǒng)設(shè)計(jì),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-06-06

