Thread safe singleton implementation in C++


The following is a well known implementation of singleton pattern in C++.
However, I'm not entirely sure whether its thread-safe.
Based upon answers to similar question asked here previously, it seems it is thread safe.
Is that so?

//Curiously Recurring Template Pattern    
//Separates a class from its Singleton-ness (almost).    
#include <iostream>  
using namespace std;

template<class T> class Singleton {
  Singleton(const Singleton&);
  Singleton& operator=(const Singleton&);
  Singleton() {}
  virtual ~Singleton() {}
  static T& instance() {
    static T theInstance;
    return theInstance;

// A sample class to be made into a Singleton
class MyClass : public Singleton<MyClass> {
 int x;
  friend class Singleton<MyClass>;
  MyClass() { x = 0; }
 void setValue(int n) { x = n; }
  int getValue() const { return x; }
6/27/2009 12:02:16 PM

Accepted Answer

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.

6/27/2009 12:07:42 PM

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow