我寫了一個單例類,使用了雙重檢查鎖定的方法,確保只有一個類實例生成。其中我使用mutex,從而實現鎖定方法。(單純的替換mutex->spinlock好像會報編譯錯誤。另外,順便問下,把mutex換成spinlock在Singleton模式下會有比較大的性能提升么?(目測不會。。。= =。。我的代碼如下:#ifndef SINGLETON#define SINGLETONclass CSingleton{public: static CSingleton* getInstance()
{ if(!uniqueInstance)
{ pthread_mutex_lock(&mutex); if(!uniqueInstance)
{
uniqueInstance = new CSingleton();
} pthread_mutex_unlock(&mutex);
} return uniqueInstance;
} void fill(int x){ val += x; } int getVal(){ return val; }private: int val; CSingleton()
{
val = 0;
} CSingleton(const CSingleton&){}
CSingleton & operator = (const CSingleton&); static CSingleton * uniqueInstance; static pthread_mutex_t mutex;
};
CSingleton * CSingleton::uniqueInstance = NULL;pthread_mutex_t CSingleton::mutex = PTHREAD_MUTEX_INITIALIZER;#endif
1 回答

明月笑刀無情
TA貢獻1828條經驗 獲得超4個贊
新的 C++11 標準增加了 2 種單例的寫法
1 static 變量是線程安全的
T& getInstance () { static T instance; return instance; }
2 使用 std::call_once,他保證了函數只會調用一次
std::once_flag flag; T* instance; T* getInstance () { std::call_once(flag, [instance]() { instance = new T; }); return instance; }
- 1 回答
- 0 關注
- 499 瀏覽
添加回答
舉報
0/150
提交
取消