C ++ 0x静态初始化和线程安全 [英] C++0x static initializations and thread safety

查看:183
本文介绍了C ++ 0x静态初始化和线程安全的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道,从C ++ 03标准来看,函数范围的静态初始化不能保证是线程安全的:

  void moo()
{
static std :: string cat(argent); // not thread safe
...
}

+ 0x标准最终提供标准的线程支持,是需要线程安全的函数范围的静态初始化吗?

解决方案

将是线程安全的,因为在对象在输入函数时动态初始化的情况下,它保证在关键部分执行:



§6.7 stmt.decl



4。 ...这样的对象在第一次控制通过其声明时被初始化...如果控制在对象被初始化时并发地执行声明,并发执行将等待初始化的完成... / p>

有一个潜在的边缘情况,如果从main()返回后,静态对象的析构函数在静态局部变量已经被销毁之后调用该函数,未定义。但是,这应该很容易避免。


I know that as of the C++03 standard, function-scope static initializations are not guaranteed to be thread safe:

void moo()
{
    static std::string cat("argent");  // not thread safe
    ...
}

With the C++0x standard finally providing standard thread support, are function-scope static initializations required to be thread safe?

解决方案

it seems the initialization would be thread safe, since in the case the object is dynamically initialized upon entering the function, it's guaranteed to be executed in a critical section:

§ 6.7 stmt.decl

4. ...such an object is initialized the first time control passes through its declaration... If control enters the declaration concurrently while the object is being initialized, the concurrent execution shall wait for completion of the initialization...

there is a potential edge-case, if after returning from main(), the destructor of a static object calls the function after the static local has already destroyed, the behavior is undefined. however, that should be easy to avoid.

这篇关于C ++ 0x静态初始化和线程安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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