c++ - Using ``spinlock`` in Singleton class
大家讲道理
大家讲道理 2017-04-17 11:08:04
[C++讨论组]

我写了一个单例类,使用了双重检查锁定的方法,确保只有一个类实例生成。

其中我使用mutex,从而实现锁定方法。

如果我想把mutex换成spinlock,我该怎么写?求一份比较详细的代码。。。

(单纯的替换mutex->spinlock好像会报编译错误。

另外,顺便问下,把mutex换成spinlock在Singleton模式下会有比较大的性能提升么?(目测不会。。。= =。。

我的代码如下:

#ifndef SINGLETON
#define SINGLETON

class 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)
PHPz

新的 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;
}
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号