C++實現一個執行緒安全的單例工廠

usher.yue發表於2015-11-07

我們見到經常有人用 static 區域性物件的方式實現了類似單例模式,最近發現一篇文章明確寫明 編譯器在處理  static區域性變數的時候 並不是執行緒安全的 !!!

http://blogs.msdn.com/b/oldnewthing/archive/2004/03/08/85901.aspx     

於是實現了一個單例工廠  並且是執行緒安全的

#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;
};

//初始化建立  後續在多執行緒中使用
//還有另一種寫法是單獨的函式直接返回內部單例包裝靜態成員在 多執行緒情況下不安全
//SingletonFactory::CreateSingletonFactory().GetInstance();
template<class T> SingletonFactory<T>* SingletonFactory<T>::CreateSingletonFactory(){
    static SingletonFactory<T> temObj;
    return &temObj;
}
//工廠例項
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

測試程式碼 

    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;


相關文章