title: How to implement multithread safe singleton in C++11 without using <mutex>
body: <p>Now that C++11 has multithreading I was wondering what is the correct way to implement lazy initialized singleton without using mutexes(for perf reasons).
  I came up with this, but tbh Im not really good at writing lockfree code, so Im looking for some better solutions.</p>
  
  <pre><code>// ConsoleApplication1.cpp : Defines the entry point for the console application.
  //
  # include &lt;atomic&gt;
  # include &lt;thread&gt;
  # include &lt;string&gt;
  # include &lt;iostream&gt;
  using namespace std;
  class Singleton
  {
  
  public:
      Singleton()
      {
      }
  static  bool isInitialized()
      {
          return (flag==2);
      }
  static  bool initizalize(const string&amp; name_)
      {
          if (flag==2)
              return false;// already initialized
          if (flag==1)
              return false;//somebody else is initializing
          if (flag==0)
          {
              int exp=0;
              int desr=1;
              //bool atomic_compare_exchange_strong(std::atomic&lt;T&gt;* obj, T* exp, T desr)
              bool willInitialize=std::atomic_compare_exchange_strong(&amp;flag, &amp;exp, desr);
              if (! willInitialize)
              {
                  //some other thread CASed before us
                  std::cout&lt;&lt;"somebody else CASed at aprox same time"&lt;&lt; endl;
                  return false;
              }
              else 
              {
                  initialize_impl(name_);
                  assert(flag==1);
                  flag=2;
                  return true;
              }
          }
      }
  static void clear()
  {
      name.clear();
      flag=0;
  }
  private:
  static  void initialize_impl(const string&amp; name_)
  {
          name=name_;
  }
  static  atomic&lt;int&gt; flag;
  static  string name;
  };
  atomic&lt;int&gt; Singleton::flag=0;
  string Singleton::name;
  void myThreadFunction()
  {
      Singleton s;
      bool initializedByMe =s.initizalize("1701");
      if (initializedByMe)
          s.clear();
  
  }
  int main()
  {
      while (true)
      {
          std::thread t1(myThreadFunction);
          std::thread t2(myThreadFunction);
          t1.join();
          t2.join();
      }
      return 0;
  }
  </code></pre>
  
  <p>Note that <code>clear()</code> is just for testing, real singleton wouldnt have that function.</p>