设计模式 - C++单例及线程安全

单例介绍

(1) 单例类保证全局只有一个唯一的实例对象。
(2) 单例类保证只有唯一的接口获取这唯一实例。

最常见的实现方式

class singleton {
private:
    /* 禁止类被构造、复制、赋值*/
    singleton() {};
    singleton(const singleton&) = delete;
    singleton& operator=(const singleton&) = delete;
    ~singleton() {};

public:
    /* 获取实例 */
    static singleton* GetInstance() {
            if (st == nullptr) {
                st = new singleton();
            }
        return st;
    };
private:
    static singleton *st;
};

上述方法存在线程安全问题,当多线程访问GetInstance()时,会引起冲突。所以很容易想到加锁的方式。

改进后加锁的实现

class singleton {
private:
    /* 禁止类被构造、复制、赋值*/
    singleton() {};
    singleton(const singleton&) = delete;
    singleton& operator=(const singleton&) = delete;
    ~singleton() {};

public:
    /* 获取实例 */
    static singleton* GetInstance() {
        if (st == nullptr) {
            mt.lock();
            if (st == nullptr) {
                st = new singleton();
            }
            mt.unlock();
        }
        return st;
    };
private:
    static singleton *st;
    static std::mutex mt;
};

上述方法线程完全安全了吗?答案是并没有。因为CPU将分配内存和赋值操作分开执行,这样会出现以下情况:

线程A:访问st为nullptr,开始分配内存;
线程A:先为st赋值,此时st未定义;
线程B:访问st不为nullptr;
线程B:使用了未定义的st;
线程A:为st分配内存。

当然绝对的线程安全还是有问题,因为C++创建对象时,会执行三步操作:

1.分配内存;
2.调用构造;
3 赋值操作;
然而现代CPU和编译器高并发下可能会进行乱序重排操作,因而创建对象new CSingleton的第2步可能会晚于第3步进行指令调用,因而导致出现未定义的的行为。

举例:

线程A : getInstance 判断 instance是否为空,为空则
线程A : 分配内存 此时CPU乱序指令重排,赋值操作提前
线程B : getInsnace 判断instance是否为空,非空,则返回
线程B : 使用了未初始化的instacne 出现未定义行为。
线程A : 调用构造函数对instance初始化。

因此要解决上述问题需要引入内存栅栏来确保指令运行的同步性。在CPU指令重排的前提下保持数据的一致性。

C++11支持线程安全的单例类

C++11的单例模式的实现

class singleton {
private:
    /* 禁止类被构造、复制、赋值*/
    singleton() {};
    singleton(const singleton&) = delete;
    singleton& operator=(const singleton&) = delete;
    ~singleton() {};

public:
    /* 获取实例 */
    static singleton* GetInstance() {
        static singleton st;
        return &st;
    };
};

完整的例子

#include "stdafx.h"
#include <string>
#include <iostream>
#include <vector>
#include <thread>
#include <mutex>
using namespace std;

class singleton {
private:
    singleton() { cout << "start" << endl;
    cout << "end" << endl;
    };
    singleton(const singleton&) = delete;
    singleton& operator=(const singleton&) = delete;
    ~singleton() {};

public:
    /*
    static singleton* GetInstance() {
        if (st == nullptr) {
            mt.lock();
            if (st == nullptr) {
                st = new singleton();
            }
            mt.unlock();
        }
        static singleton st;
        return st;
    };
    */

    static singleton* GetInstance() {
        static singleton st;
        return &st;
    };
    void print() {
        mt.lock();
        cout << "print" << endl; 
        cout<< ++mm << endl; 
        mt.unlock();
    };

private:
    static std::mutex mt;
    //static singleton *st;
    int mm;
};

//ingleton* singleton::st = nullptr;
std::mutex singleton::mt;

void thread_func()
{
    singleton *p = singleton::GetInstance();
    for(auto i=0; i<1; i++)
        p->print();
}
int main()
{
    vector<thread> vthrd;
    for (auto i = 0; i < 100; i++)
    {
        vthrd.push_back(std::thread(thread_func));
    }

    for (auto iter = vthrd.begin(); iter != vthrd.end(); iter++)
    {
        (*iter).join();
    }
    return 0;
}

参考

C++11 单例类实现
c++的单例模式及c++11对单例模式的优化

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值