title: Why does this C++ static singleton never stop?
body: <p>i have implemented a singleton (static version) in C++. I know all the controversy about this pattern and potential thread-safety issues, but i am curious why this exact implementation won't halt. The program never quits, it remains in a deadlock state at the end.</p>
  
  <p>singleton.h:</p>
  
  <pre><code>#pragma once
  #include &lt;thread&gt;
  #include &lt;atomic&gt;
  
  class Singleton
  {
  public:
      static Singleton&amp; getInstance();
  
  private:
      std::thread mThread;
      std::atomic_bool mRun;
  
      Singleton();
      ~Singleton();
      void threadFoo();
  };
  </code></pre>
  
  <p>singleton.cpp</p>
  
  <pre><code>#include "singleton.h"
  
  Singleton&amp; Singleton::getInstance()
  {
      static Singleton instance;
      return instance;
  } 
  
  Singleton::Singleton()
  {
      mRun.store(true);
      mThread = std::thread(&amp;Singleton::threadFoo, this);
  }
  
  Singleton::~Singleton()
  {
      mRun.store(false);
  
      if(mThread.joinable())
          mThread.join();
  }
  
  void Singleton::threadFoo()
  {
      while(mRun)
      {
      }
  }
  </code></pre>
  
  <p>main.cpp</p>
  
  <pre><code>#include "singleton.h"
  
  int main()
  {
      Singleton::getInstance();
      return 0;
  }
  </code></pre>
  
  <p>What I already know:</p>
  
  <ul>
  <li>the thread terminates</li>
  <li>the main thread is stuck in the join</li>
  <li>it has something to do with the static, if i make the constructor public and create an instance of Singleton in main() it will correctly terminate.</li>
  </ul>
  
  <p>Using Visual Studio 2012. Thanks for your advice.</p>