在以下场景中:
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/