-2

I'm writing code that maybe run under c++03(or c++98), I want to know whether the function static variable initialization guranteed to be thread-safe:

void foo() {
  static X x; // Is it thread-safe for the construction of x if foo() is called from multiple threads?
  ...
}
konchy
  • 573
  • 5
  • 16
  • 3
    There were no threads before C++11 – Mat Aug 02 '23 at 05:28
  • No it was not threadsafe. That was added in C++11, with thread – Pepijn Kramer Aug 02 '23 at 05:28
  • 1
    @Mat: Nonsense. There were no *standard* threads before C++11, but people wrote thread-safe code beforehand. – Nicol Bolas Aug 02 '23 at 05:29
  • 1
    @NicolBolas: this is tagged language-lawyer – Mat Aug 02 '23 at 05:29
  • 1
    @Mat There is not much to language-lawyer on. Threadsafety wasn't mentioned prior to C++11 (in conjunction with the static keyword), so one could not assume static initializationwas threadsafe in any way – Pepijn Kramer Aug 02 '23 at 05:30
  • It is not guaranteed to be thread safe for compilers using C++03 or C++98 standards. [This question](https://stackoverflow.com/questions/28096970/when-is-a-divide-by-zero-not-a-divide-by-zero-a-puzzle-in-the-debugger-static) shows the issue with code written before C++11, or code that didn't adhere to C++11 standards. – PaulMcKenzie Aug 02 '23 at 07:43

2 Answers2

2

While non-standard means of writing thread-safe code have existed since threading began, the thread-safety of static variables was never something that compilers provided on their own. It was mandated by C++11 and if some pre-C++11 compilers provided it, it would only be as early implementations of C++11.

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
  • 1
    I think gcc's implementation was thread safe long before c++11. Visual studio only added it in 2015 – Alan Birtles Aug 02 '23 at 07:02
  • @AlanBirtles -- And even with VS 2015, it wasn't until (I believe) service pack 3 for VS 2015 did MS finally implement thread-safety for static variables. – PaulMcKenzie Aug 02 '23 at 07:48
  • @PaulMcKenzie no mention of that in the documentation https://learn.microsoft.com/en-us/cpp/build/reference/zc-threadsafeinit-thread-safe-local-static-initialization?view=msvc-170 – Alan Birtles Aug 02 '23 at 07:54
  • ok, I may be wrong, It may have been other C++11 aspects that were not implemented until SP 3. – PaulMcKenzie Aug 02 '23 at 08:03
0

The standard didn't acknowledge the existence of threads until C++11. As far as the C++ standard was concerned, it was as thread-safe as it was unicorn-safe. Different implementations were of course free to implement or ignore thread-safety (and unicorn-safety!).

Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93