這篇文章主要介紹C++如何實(shí)現(xiàn)一個(gè)線程安全的單例工廠,文中介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們一定要看完!
創(chuàng)新互聯(lián)公司主要從事成都網(wǎng)站制作、成都網(wǎng)站建設(shè)、外貿(mào)營(yíng)銷網(wǎng)站建設(shè)、網(wǎng)頁(yè)設(shè)計(jì)、企業(yè)做網(wǎng)站、公司建網(wǎng)站等業(yè)務(wù)。立足成都服務(wù)哈爾濱,十余年網(wǎng)站建設(shè)經(jīng)驗(yàn),價(jià)格優(yōu)惠、服務(wù)專業(yè),歡迎來(lái)電咨詢建站服務(wù):18980820575
C++實(shí)現(xiàn)一個(gè)線程安全的單例工廠實(shí)現(xiàn)代碼
我們見(jiàn)到經(jīng)常有人用 static 局部對(duì)象的方式實(shí)現(xiàn)了類似單例模式,最近發(fā)現(xiàn)一篇文章明確寫明 編譯器在處理 static局部變量的時(shí)候 并不是線程安全的 ?。。?/p>
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;
以上是“C++如何實(shí)現(xiàn)一個(gè)線程安全的單例工廠”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對(duì)大家有幫助,更多相關(guān)知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道!
名稱欄目:C++如何實(shí)現(xiàn)一個(gè)線程安全的單例工廠
當(dāng)前URL:http://muchs.cn/article18/picegp.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供ChatGPT、網(wǎng)站維護(hù)、標(biāo)簽優(yōu)化、虛擬主機(jī)、搜索引擎優(yōu)化、手機(jī)網(wǎng)站建設(shè)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)