Visual Studio 2012 does not implement the C++11 standard for thread safe static initialization (http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2660.htm). I have a function local static that I need to guarantee will be initialized in a thread safe way. The following is not thread safe in Visual Studio 2012:
struct MyClass { int a; MyClass() { std::this_thread::sleep_for(std::chrono::milliseconds(100)); a = 5; } }; void foo() { static MyClass instance; std::cout << instance.a << '\n'; } int main() { std::thread a(foo); std::thread b(foo); a.join(); b.join(); system("pause"); } The output of the above program on Visual Studio 2012 will most likely be:
0 5 I need to work around this problem and I am trying to find a way to do it with function local statics only (no globals or class level statics).
My initial thought was to use a mutex, but it suffers from the same problem of static initialization thread safety. If I have a static st::mutex inside of foo it is possible that the second thread will get a copy of the mutex while it is in an invalid state.
Another option is to add an std::atomic_flag spin-lock. The question is, is std::atomic_flag initialization thread safe in Visual Studio 2012?
void foo() { // is this line thread safe? static std::atomic_flag lock = ATOMIC_FLAG_INIT; // spin lock before static construction while (lock.test_and_set(std::memory_order_acquire)); // construct an instance of MyClass only once static MyClass instance; // end spin lock lock.clear(std::memory_order_release); // the following is not thread safe std::cout << instance.a << '\n'; } In the above code, is it possible for both threads to get past the spin lock or is it guaranteed that only one of them will? Unfortunately I can't think of an easy way to test this since I can't put something inside the atomic_flag initializer to slow it down like I can with a class. However, I want to be sure that my program won't crash once in a blue moon because I made an invalid assumption.