Function-scope static initialization C++11 thread-safe guard variance across compilers
0 reputation · 18 Dec 2020, 08:46 UTC
Function-scope static variables are required by C++11 and later to be initialized in a thread-safe manner. The Standard mandates the single-initialization guarantee but does not specify the synchronization mechanism, leaving the lock type and algorithm to the implementation.
The feature is relevant for code paths hit by many concurrent requests where the first entry to a function triggers initialization. Because the guard is implementation-defined, the cost and contention profile can differ between compilers and standard library configurations, creating an unresolved design decision for latency-sensitive code.
What synchronization primitive is used to guard first-time initialization of a function-scope static in a specific compiler and library combination? How does that choice influence contention when multiple threads concurrently enter the same function for the first time? Is there a portable way to reason about the initialization cost without implementation-specific inspection?