c++ - 在 C++ 中,原始类型静态初始化为常量值是线程安全的吗?

标签 c++ static multithreading constants

即,即使在多线程环境中,以下内容是否也能正确执行?

int dostuff(void) {
    static int somevalue = 12345;
    return somevalue;
}

或者是否有可能让多个线程调用它,并在执行开始之前调用一次返回 &somevalue 处的任何垃圾?

最佳答案

标准的第 6.7 节是这样说的:

The zero-initialization of all local objects with static storage duration is performed before any other initialization takes place. A local object of POD type with static storage duration initialized with constant-expressions is initialized before its block is first entered. An implementation is permitted to perform early initialization of other local objects with static storage duration under the same conditions that an implementation is permitted to statically initialize an object with static storage duration in namespace scope. 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. If control re-enters the declaration (recursively) while the object is being initialized, the behavior is undefined.

因此,如果它是 POD 类型,那么看起来初始化发生在启动时,然后才能启动新线程。对于非 POD 类型,它更复杂,标准说行为是未定义的(除非在其他地方它说了一些关于初始化期间线程安全的事情)。

我碰巧知道,当初始化一个非 POD 对象时,GCC 会获取一个互斥锁以防止它被初始化两次(我知道这一点是因为我曾经不小心递归初始化一个静态对象而导致程序死锁)。

很遗憾,我无法告诉您这是其他编译器的情况还是标准中其他地方强制要求的。

关于c++ - 在 C++ 中,原始类型静态初始化为常量值是线程安全的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2180501/

相关文章:

multithreading - MS Access 中的 VBA + 线程

c++ - 一秒钟有多少滴答声?

c++ - 比较非静态函数中的静态和非静态整数

python - 如何使用字典作为输入进行多线程?

c - 并行编程=多子进程还是每个进程创建一个子进程?

xcode - 在Xcode 4中构建静态库。$ {BUILD_STYLE}会发生什么?

c++ - Google Test中的测试类的构造方法

c++ - 在 libc++ 的 istringstream 的析构函数中未定义对运算符 delete 的引用

c++ - libjpeg 将图像写入内存数据

c++ - 动态分配数组和静态数组的区别