c++ - C++11 中的静态变量初始化是同步的吗?

标签 c++ multithreading c++11 static initialization

在以下场景中:

HeavyInitClass* f()
{
    static HeavyInitClass* heavy = new HeavyInitClass();
    return heavy;
}

我知道在 C++11 中,heavy 在多线程环境中将被初始化一次,因为标记 heavy 未初始化的标志是线程安全的。

但是它是否也会阻塞线程,直到重载被初始化为止? 如果100个线程同时调用f(),那么其他99个线程是否会等待直到初始化线程完成初始化?

非常感谢!

最佳答案

这是标准第 §6.7 [stmt.dcl]/p4 规定的:

If control enters the declaration concurrently while the variable is being initialized, the concurrent execution shall wait for completion of the initialization.

换句话说,是的。其他线程必须阻塞,直到初始化完成。

关于c++ - C++11 中的静态变量初始化是同步的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23593800/

相关文章:

c++ - undefined reference 错误的含义

c# - 在没有等待的情况下使用异步的最佳实践是什么?

c++ - 在 C++ 中获取类对象的地址?

c++ - 优化光线追踪器中的 BVH 遍历

ruby - 生产者/消费者的特例

java - 并行执行竞争计算并丢弃除第一个完成的计算之外的所有计算

c++ - 在 C++11 中处理毫秒的正确方法是什么

c++ - enable_shared_from_this 需要什么?

c++11 - C++为什么 "A a();"不会调用构造函数

c++ - 在同一连接或拆分连接上流式传输视频和命令?