Std :: thread :: hardware_concurrency and static initialization

Can this global function suffer from a static initialization fiasco?

template <typename TFn> void ParallelFor(int iIni,int iFin,TFn Fn) { static const unsigned int NThread= std::thread::hardware_concurrency(); // ... } 
+8
c ++ multithreading static c ++ 11 static-order-fiasco
source share
1 answer

Can this global function suffer from a static initialization fiasco?

No, it will not. Are you safe ... :-)

Quoting a standard C ++ draft (highlighting my focus) ...

$ 6.7: 4: Dynamic initialization of a variable region of a block using static storage duration ([basic.stc.static]) or thread storage duration ([basic.stc.thread]) is executed for the first time through its declaration; such a variable is considered initialized after completion of its initialization. If initialization is completed by throwing an exception, initialization is not completed, so it will be checked again the next time the declaration is made. If the control enters the declaration simultaneously while the variable is being initialized, simultaneous execution should wait for the initialization to complete

Also see: Static Local Variables

Since your function is a template function template <typename TFn> , for each individual instance (substitution TFn ), static const unsigned int NThread = std::thread::hardware_concurrency(); will be evaluated

+7
source share

All Articles