Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++0x static initializations and thread safety

I know that as of the C++03 standard, function-scope static initializations are not guaranteed to be thread safe:

void moo()
{
    static std::string cat("argent");  // not thread safe
    ...
}

With the C++0x standard finally providing standard thread support, are function-scope static initializations required to be thread safe?

like image 733
R Samuel Klatchko Avatar asked Jan 01 '10 01:01

R Samuel Klatchko


People also ask

Are static variables thread-safe C?

Thread SafetyStatic variables are not thread safe. Instance variables do not require thread synchronization unless shared among threads. But, static variables are always shared by all the threads in the process.

Does static make thread-safe?

A data type or static method is threadsafe if it behaves correctly when used from multiple threads, regardless of how those threads are executed, and without demanding additional coordination from the calling code.

Are static objects thread-safe C++?

C++11 has this neat feature: static objects are initialized in a thread-safe manner. This is yet another post on how it is done. First things first: The Standard (well, at least the freely available draft). Here's what it says about static object initialization (6.7.


1 Answers

it seems the initialization would be thread safe, since in the case the object is dynamically initialized upon entering the function, it's guaranteed to be executed in a critical section:

§ 6.7 stmt.decl

4. ...such an object is initialized the first time control passes through its declaration... If control enters the declaration concurrently while the object is being initialized, the concurrent execution shall wait for completion of the initialization...

there is a potential edge-case, if after returning from main(), the destructor of a static object calls the function after the static local has already destroyed, the behavior is undefined. however, that should be easy to avoid.

like image 137
jspcal Avatar answered Oct 09 '22 05:10

jspcal