c++c++11thread-safetydouble-checked-locking

C++11: Safe double checked locking for lazy initialization. Possible?


I have read many questions considering thread-safe double checked locking (for singletons or lazy init). In some threads, the answer is that the pattern is entirely broken, others suggest a solution.

So my question is: Is there a way to write a fully thread-safe double checked locking pattern in C++? If so, how does it look like.

We can assume C++11, if that makes things easier. As far as I know, C++11 improved the memory model which could yield the needed improvements.

I do know that it is possible in Java by making the double-check guarded variable volatile. Since C++11 borrowed large parts of the memory model from the one of Java, so I think it could be possible, but how?


Solution

  • Simply use a static local variable for lazily initialized Singletons, like so:

    MySingleton* GetInstance() {
      static MySingleton instance;
      return &instance; 
    }
    

    The (C++11) standard already guarantees that static variables are initialized in a threadsafe manner and it seems likely that the implementation of this at least as robust and performant as anything you'd write yourself.

    The threadsafety of the initialization can be found in §6.7.4 of the (C++11) standard:

    If control enters the declaration concurrently while the variable is being initialized, the concurrent execution shall wait for completion of the initialization.