Thread safe singleton implementation in C++ Thread safe singleton implementation in C++ multithreading multithreading

Thread safe singleton implementation in C++


No, this is not thread safe because the static local is not guarded in any way. By default a static local is not thread safe. This means you could run into the following issues

  • Constructor for the singleton runs more than once
  • The assignment to the static is not guaranteed to be atomic hence you could see a partial assignment in multi-threaded scenarios
  • Probably a few more that I'm missing.

Here is a detailed blog entry by Raymond Chen on why C++ statics are not thread safe by default.


IT IS NOT THREAD SAFE.To become thread safe you should add a check before the lock (semaphore lock) and an other check after the lock. And then you are sure that even in simultaneous call from different threads you provide one instance.


It's not threadsafe, unless you configure your compiler to generate threadsafe code for static accesses.

However, it's better that the code be self contained, so I'd add a mutex here and there.