设计模式 - 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 
#include 
#include 
#include 
#include 
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 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对单例模式的优化

你可能感兴趣的:(架构设计学习专题)