Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::thread::hardware_concurrency and static initialization

May this global function suffer from static initialization fiasco?

template <typename TFn>
void ParallelFor(int iIni,int iFin,TFn Fn)    
{
  static const unsigned int NThread= std::thread::hardware_concurrency();
  // ...    
}
like image 940
metalfox Avatar asked Jun 06 '16 06:06

metalfox


1 Answers

May this global function suffer from static initialization fiasco?

No, it wouldn't. You are safe... :-)

Quoting the C++ standard draft (emphasis mine)...

$6.7: 4: Dynamic initialization of a block-scope variable with static storage duration ([basic.stc.static]) or thread storage duration ([basic.stc.thread]) is performed the first time control passes through its declaration; such a variable 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 enters the declaration concurrently while the variable is being initialized, the concurrent execution shall wait for completion of the initialization

Also, see: Static local variables

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

like image 148
WhiZTiM Avatar answered Oct 08 '22 18:10

WhiZTiM