10

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?

Rob
  • 76,700
  • 56
  • 158
  • 197
R Samuel Klatchko
  • 74,869
  • 16
  • 134
  • 187
  • 3
    I think as of today it will be called C++1x –  Jan 01 '10 at 02:29
  • Bjarne Stoustrup says to think of the x as a hexidecimal number, so still 0x – John Dibling Jan 01 '10 at 05:29
  • @John: Regardless of what he may think or like, my understanding is that ISO guidelines require versioning of documents such as standards to be in base-10. –  Jan 01 '10 at 10:37
  • 5
    ISO guidelines have nothing to do with it, as C++0x isn't the formal name of the standard. Never was, never will be. And the same goes for C++1x. It's not an ISO name, so ISO's rules don't matter. – jalf Jan 01 '10 at 15:12

1 Answers1

9

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.

jspcal
  • 50,847
  • 7
  • 72
  • 76
  • 3
    Famous last words "should be easy to avoid". It is tremendously difficult to avoid in the general case. – deft_code Jan 28 '10 at 01:21