c++ - block 范围静态的析构函数可以被调用几次?

标签 c++ multithreading c++11

我刚刚读了this有关当前 boost::mutex 实现背后实际原因的文章,并注意到以下短语:

Block-scope statics have the additional problem of a potential race condition on "the first time through", which can lead to the destructor being run multiple times on popular compilers, which is undefined behaviour — compilers often use the equivalent of a call to atexit in order to ensure that destruction is done in the reverse order of construction, and the initialization race that may cause the constructor to be run twice may also cause the destructor to be registered twice

这是真的吗?我真的应该通过原子操作或类似的方式检查另一个线程是否已经在这个对象的析构函数中吗?即使在 C++11 - C++14 中我也应该这样做吗?因为据我所知,自 C++11 以来,不再有“可以从多个线程同时调用具有静态存储持续时间的同一本地对象的构造函数”的问题——它要求另一个线程应该等待构造函数的完成。我说得对吗?

最佳答案

看起来这篇文章是在 C++11 之前写的,其中包括:

[...] next version of the C++ Standard, scheduled to be released in 2009.[...]

这是 C++11 之前的情况,由于线程不是 C++11 之前的内存模型的一部分,因此未指定在这种情况下发生了什么。

这在 C++11 和 draft C++11 standard 中发生了变化6.7 声明语句 说(强调我的):

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 之前,我们必须像对待任何其他临界区一样对待静态局部变量。我们可以在帖子 C++ scoped static initialization is not thread-safe, on purpose! 中找到对 C++11 之前情况的出色描述。 .

关于c++ - block 范围静态的析构函数可以被调用几次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33689895/

相关文章:

c++ - 嵌入 OpenCV Viz3d 和 Qt

c++ - 为什么 deque 的 pop_front() 和 pop_back() 不是 noexcept?

c++ - 什么时候应该使用 decltype(x) 而不是 auto 来声明变量的类型?

c++ - map和unordered_map相关的编译错误 : "attempting to reference a deleted function"

c++ - 如何预先计算值数组?

c++ - 如何在 opengl 上为两个重叠对象设置混合功能

java - 如何在 WebSphere 下停止应用程序的后台线程

c++ - 在另一个线程 visual studio 2012 中看不到 std::string 的变化

java - 将数据传递到 Runnable 的最佳方法是什么?

c++ - 如何将带有缓冲区的对象从插件发送到 Node 线程安全?