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++11/14 線程中使用Lambda函數(shù)的方法
這篇文章主要介紹了C++11/14 線程中使用Lambda函數(shù)的方法,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2019-01-01
QT編寫簡(jiǎn)單登錄界面的實(shí)現(xiàn)示例
登陸界面是網(wǎng)頁中常見的界面,本文主要介紹了QT編寫簡(jiǎn)單登錄界面的實(shí)現(xiàn)示例,具有一定的參考價(jià)值,感興趣的可以了解一下2024-02-02
C++11的函數(shù)包裝器std::function使用示例
C++11引入的std::function是最常用的函數(shù)包裝器,它可以存儲(chǔ)任何可調(diào)用對(duì)象并提供統(tǒng)一的調(diào)用接口,以下是關(guān)于函數(shù)包裝器的詳細(xì)講解,包括它的基本用法、特點(diǎn)、限制、以及與其他相關(guān)機(jī)制的對(duì)比2024-12-12
C++?構(gòu)造函數(shù)學(xué)習(xí)筆記
這篇文章主要為大家介紹了C++?構(gòu)造函數(shù)學(xué)習(xí)筆記,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-10-10
解析C++無鎖隊(duì)列的實(shí)現(xiàn)代碼
本篇文章是對(duì)C++無鎖隊(duì)列的實(shí)現(xiàn)進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-05-05

