返回本地静态对象线程安全的pre-c ++ 11编译器 [英] Is returning local static object thread safe for pre-c++11 compilers

查看:112
本文介绍了返回本地静态对象线程安全的pre-c ++ 11编译器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个单例程序线程对于预C ++ 11编译器是否安全?
我们知道对于C ++ 11它是线程安全的。

Is this singleton thread safe for the pre-C++11 compilers ? As we know for C++11 it is thread safe.

class Singleton
{
private:
   Singleton(){};

public:
   static Singleton& instance()
   {
      static Singleton INSTANCE;
      return INSTANCE;
   }
};


推荐答案

在C ++ 11中,以下内容来自 C ++ 11标准草案 的 部分:
$ b $ b

In C++11 what makes this thread safe is the following from the draft C++11 standard section 6.7 Declaration statement which says (emphasis mine):


所有具有静态
存储持续时间(3.7.1)或线程存储持续时间(3.7.2)的块范围变量的零初始化(8.5)是
在任何其他初始化之前执行。 [...]否则
这样的变量初始化时第一次控制通过
它的声明;这样的变量被认为在
完成其初始化时被初始化。如果初始化由
抛出异常,则初始化不完成,因此在下一次控制进入声明时将再次尝试
如果
控制在初始化变量
的同时输入声明,则并发执行将等待初始化的完成
[...] p>

The zero-initialization (8.5) of all block-scope variables with static storage duration (3.7.1) or thread storage duration (3.7.2) is performed before any other initialization takes place. [...] Otherwise such a variable is initialized the first time control passes through its declaration; such a variable is considered initialized upon the completion of its initialization. If the initialization exits by throwing an exception, the initialization is not complete, so it will be tried again the next time control enters the declaration. If control enters the declaration concurrently while the variable is being initialized, the concurrent execution shall wait for completion of the initialization. [...]

而前C ++ 11节 6.7 说:

while pre C++11 section 6.7 says:


[...]否则,这样的对象在第一次通过
通过其声明时被初始化;这样的对象被认为是在
初始化完成其初始化时。如果初始化退出
抛出一个异常,初始化是不完整的,所以它将
再次尝试下一次控制输入声明。[...]

[...]Otherwise such an object is initialized the first time control passes through its declaration; such an object is considered initialized upon the completion of its initialization. If the initialization exits by throwing an exception, the initialization is not complete, so it will be tried again the next time control enters the declaration.[...]

它不具有与C ++ 11具有相同的保证,所以它似乎预先的C ++ 11它没有指定,因此你不能指望它。虽然这并不妨碍实现提供更强的保证。

which does not have the same guarantee that C++11 has and so it would seem pre C++11 it is not specified and therefore you can not count on it. Although this does not prevent implementations from making stronger guarantees.

这是有意义的,因为pre C ++ 11内存模型没有包含线程。

This make sense since pre C++11 the memory model did not including threading.

这篇关于返回本地静态对象线程安全的pre-c ++ 11编译器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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