用C++实现单例模式4——C++11实现

1.static local 
    Scott Meyer在《Effective C++》中提出了一种简洁的singleton写法。
template<typename T>
class Singleton
{
public:
static T& getInstance()
{
    static T value;
    return value;
}
private:
    Singleton();
    ~Singleton();
};
    先说结论:
       *单线程下,正确。
       *C++11及以后的版本(如C++14)的多线程下,正确。
        *C++11之前的多线程下,不一定正确。
   原因在于在C++11之前的标准中并没有规定local static变量的内存模型,所以很多编译器在实现local static变量的时候仅仅是进行了一次check(参考《深入探索C++对象模型》),于是getInstance函数被编译器改写成这样了:
bool initialized = false;
char value[sizeof(T)];
T& getInstance()
{
    if (!initialized)
    {
        initialized = true;
        new (value) T();
    }
    return *(reinterpret_cast<T*>(value));
}
     于是乎它就是不是线程安全的了。
     但是在C++11却是线程安全的,这是因为新的C++标准规定了当一个线程正在初始化一个变量的时候,其他线程必须得等到该初始化完成以后才能访问它.
     在C++11 standard中的§6.7 [stmt.dcl] p4:
If control enters the declaration concurrently while the variable is being initialized, the concurrent execution shall wait for completion of the initialization.


2.atomic_thread_fence
    关于memory fence,不同的CPU,不同的编译器有不同的实现方式,要是直接使用还真是麻烦,不过,c++11中对这一概念进行了抽象,提供了方便的使用方式
    在c++11中,可以获取(acquire/consume)和释放(release)内存栅栏来实现上述功能。使用c++11中的atomic类型来包装m_instance指针,这使得对m_instance的操作是一个原子操作。下面的代码演示了如何使用内存栅栏:
std::atomic<Singleton*> Singleton::m_instance;
std::mutex Singleton::m_mutex;

Singleton* Singleton::getInstance() {
    Singleton* tmp = m_instance.load(std::memory_order_relaxed);
    std::atomic_thread_fence(std::memory_order_acquire);  
    if (tmp == nullptr) {
        std::lock_guard<std::mutex> lock(m_mutex);
        tmp = m_instance.load(std::memory_order_relaxed);
        if (tmp == nullptr) {
            tmp = new Singleton;
            std::atomic_thread_fence(std::memory_order_release); 
            m_instance.store(tmp, std::memory_order_relaxed);
        }
    }
    return tmp;
}
     上面的代码中atomic_thread_fence在创建对象线程和使用对象线程之间建立了一种“同步-与”的关系(synchronizes-with)。
      以下是摘自cplusplus关于atomic_thread_fence函数的说明:
           Establishes a multi-thread fence: The point of call to this function becomes either an acquire or a release synchronization point (or both). 
          All visible side effects from the releasing thread that happen before the call to this function are synchronized to also happen before the call this function in the acquiring thread. 
          Calling this function has the same effects as a load or store atomic operation, but without involving an atomic value

    中文大意是创建一个多线程栅栏,调用该函数的位置成为一个(acquire或release或两者)的同步点, 
    在release线程中此同步点之前的数据更新都将同步于acquire 线程的同步点之前,这就实现线程可见性一致


3.atomic
      上节的代码使用内存栅栏锁定技术可以很方便地实现双重检查锁定。但是看着实在有点麻烦,在C++11中更好的实现方式是直接使用原子操作.
std::atomic<Singleton*> Singleton::m_instance;
std::mutex Singleton::m_mutex;

Singleton* Singleton::getInstance() {
    Singleton* tmp = m_instance.load(std::memory_order_acquire);
    if (tmp == nullptr) {
        std::lock_guard<std::mutex> lock(m_mutex);
        tmp = m_instance.load(std::memory_order_relaxed);
        if (tmp == nullptr) {
            tmp = new Singleton;
            m_instance.store(tmp, std::memory_order_release);
        }
    }
    return tmp;
}
      如果你对memory_order的概念还是不太清楚,那么就使用C++顺序一致的原子操作,所有std::atomic的操作如果不带参数默认都是std::memory_order_seq_cst,即顺序的原子操作(sequentially consistent),简称SC,使用(SC)原子操作库,整个函数执行指令都将保证顺序执行,这是一种最保守的内存模型策略。
    下面的代码就是使用SC原子操作实现双重检查锁定。
std::atomic<Singleton*> Singleton::m_instance;
std::mutex Singleton::m_mutex;

Singleton* Singleton::getInstance() {
    Singleton* tmp = m_instance.load();
    if (tmp == nullptr) {
        std::lock_guard<std::mutex> lock(m_mutex);
        tmp = m_instance.load();
        if (tmp == nullptr) {
            tmp = new Singleton;
            m_instance.store(tmp);
        }
    }
    return tmp;
}
4.call_once(最简单的实现)
     在多线程编程中,有一个常见的情景是某个任务只需要执行一次。在C++11中提供了很方便的辅助类once_flag,call_once。
     以下是对std::call_once的原文说明:
         rom:std::call_once@cplusplus.com 
         Calls fn passing args as arguments, unless another thread has already executed (or is currently executing) a call to call_once with the same flag. 
        If another thread is already actively executing a call to call_once with the same flag, it causes a passive execution: Passive executions do not call fn but do not return until the active execution itself has returned, and all visible side effects are synchronized at that point among all concurrent calls to this function with the same flag. 
If an active call to call_once ends by throwing an exception (which is propagated to its calling thread) and passive executions exist, one is selected among these passive executions, and called to be the new active call instead. 
         Note that once an active execution has returned, all current passive executions and future calls to call_once (with the same flag) also return without becoming active executions. 
       The active execution uses decay copies of the lvalue or rvalue references of fn and args, ignoring the value returned by fn.
also see: 


大意就是:
     call_one保证函数fn只被执行一次,如果有多个线程同时执行函数fn调用,则只有一个活动线程(active call)会执行函数,其他的线程在这个线程执行返回之前会处于”passive execution”(被动执行状态)—不会直接返回,直到活动线程对fn调用结束才返回。对于所有调用函数fn的并发线程的数据可见性都是同步的(一致的)。 
     如果活动线程在执行fn时抛出异常,则会从处于”passive execution”状态的线程中挑一个线程成为活动线程继续执行fn,依此类推。 
    一旦活动线程返回,所有”passive execution”状态的线程也返回,不会成为活动线程。
     由上面的说明,我们可以确信call_once完全满足对多线程状态下对数据可见性的要求。
    所以利用call_once再结合lambda表达式,前面几节那么多复杂代码,在这里千言万语凝聚为一句话:

Singleton* Singleton::m_instance;
Singleton* Singleton::getInstance() {
    static std::once_flag oc;//用于call_once的局部静态变量
    std::call_once(oc, [&] {  m_instance = new Singleton();});
    return m_instance;
}
总结
本文中提到的几种方法都是安全可用的方案,具体用哪种,我个人觉得还是call_once最简单,我肯定选call_one。但不代表前面的那么多都白写了,其实学习每种方法过程中让我对c++11内存模型有了更深入的理解,这才是最大的收获。






  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

X-Programer

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值