Question

In the following scenario:

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

I know that in C++11 heavy will be initialized exactly once in a multithreaded environment because the flag that marks that heavy was not initialized is thread-safe.

BUT does it also block the threads until heavy has been initialized? If 100 threads call f() in the same time, does the 99 other threads wait until the initializing thread finishes the initialization?

Thanks a lot!

Was it helpful?

Solution

This is mandated by §6.7 [stmt.dcl]/p4 of the standard:

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

In other words, yes. The other threads must block until initialization is complete.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top