title: Waiting for a std::thread to finish
body: <p>I am trying to clean up gracefully on program termination, so I'm calling <code>join()</code> on a <code>std::thread</code> to wait for it to finish. This simply seems to block the main thread forever, but I don't understand why, because the worker thread is an (almost) empty loop like this:</p>
  
  <pre><code>void GameLoop::Run()
  {
      while (run)
      {
          //  Do stuff... 
      }   
      std::cout &lt;&lt; "Ending thread...\n";
  }
  </code></pre>
  
  <p>I'm setting <code>run</code> to false before <code>join</code>ing, of course. Now, I'm suspecting it's got something to do with it being a member function and being called upon object <em>destruction</em>. I'm creating the thread like this: <code>runThread.reset(new thread(&amp;GameLoop::Run, this));</code>, where <code>runThread</code> is <code>unique_ptr&lt;std::thread&gt;</code> and a member of <code>GameLoop</code>. The <code>join()</code> call comes in the destructor of the <code>GameLoop</code> object. </p>
  
  <p>Maybe the loop thread cannot finish if its object is in the process of being destroyed? According to the debugger the loop thread lingers on in the dark depths of <code>msvcr120d.dll</code>. If so, how would you handle it?</p>
  
  <p>Beware: new to <code>std::thread</code> here!</p>
  
  <p><strong>Update:</strong> This is my call to join in the destructor:</p>
  
  <pre><code>run = false;
  if (runThread-&gt;joinable())
  {
      runThread-&gt;join();
  }
  </code></pre>
  
  <p><strong>Update 2:</strong> If I remove the <code>join()</code> I get an exception raised by <code>~thread()</code>!</p>