亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如果我想把mutex換成spinlock,我該怎么寫啊?

如果我想把mutex換成spinlock,我該怎么寫???

C++
波斯汪 2023-05-03 17:13:00
我寫了一個單例類,使用了雙重檢查鎖定的方法,確保只有一個類實例生成。其中我使用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;
}
查看完整回答
反對 回復 2023-05-06
  • 1 回答
  • 0 關注
  • 499 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號