gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 15:46:03 27 4
gpt4 key购买 nike

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

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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com