线程安全单例实现在C ++中 [英] Thread safe singleton implementation in C++

查看:126
本文介绍了线程安全单例实现在C ++中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是C ++中公知的单例模式的实现。

但是,我不完全确定它的线程安全性。

根据类似问题的答案以前在这里问过,它似乎是线程安全的。

是这样吗?

  //奇怪的循环模板模式
//将类与其Singleton-ness(几乎)分开。
#include< iostream>
使用命名空间std;

模板< class T> Singleton课程{
Singleton(const Singleton&);
Singleton& operator =(const Singleton&);
protected:
Singleton(){}
virtual〜Singleton(){}
public:
static T& instance(){
static T theInstance;
return theInstance;
}
};

//要创建为Singleton的样本类
class MyClass:public Singleton< MyClass> {
int x;
protected:
friend class Singleton< MyClass> ;;
MyClass(){x = 0; }
public:
void setValue(int n){x = n; }
int getValue()const {return x; }
};


解决方案

不,这不是线程安全的,因为静态本地没有任何保护。默认情况下,静态本地不是线程安全的。这意味着您可能遇到以下问题




  • 单身份的构造方法多次运行

  • 对static的赋值不能保证是原子的,因此您可以在多线程方案中看到部分赋值。

  • 可能还有一些我失踪了。



这是Raymond Chen的详细博客条目,为什么默认情况下C ++静态不是线程安全的。




The following is a well known implementation of singleton pattern in C++.
However, I'm not entirely sure whether its thread-safe.
Based upon answers to similar question asked here previously, it seems it is thread safe.
Is that so?

//Curiously Recurring Template Pattern    
//Separates a class from its Singleton-ness (almost).    
#include <iostream>  
using namespace std;

template<class T> class Singleton {
  Singleton(const Singleton&);
  Singleton& operator=(const Singleton&);
protected:
  Singleton() {}
  virtual ~Singleton() {}
public:
  static T& instance() {
    static T theInstance;
    return theInstance;
  }
};

// A sample class to be made into a Singleton
class MyClass : public Singleton<MyClass> {
 int x;
protected:
  friend class Singleton<MyClass>;
  MyClass() { x = 0; }
public:
 void setValue(int n) { x = n; }
  int getValue() const { return x; }
};

解决方案

No, this is not thread safe because the static local is not guarded in any way. By default a static local is not thread safe. This means you could run into the following issues

  • Constructor for the singleton runs more than once
  • The assignment to the static is not guaranteed to be atomic hence you could see a partial assignment in multi-threaded scenarios
  • Probably a few more that I'm missing.

Here is a detailed blog entry by Raymond Chen on why C++ statics are not thread safe by default.

这篇关于线程安全单例实现在C ++中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆