为了账号安全,请及时绑定邮箱和手机立即绑定

如果我想把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 关注
  • 332 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信