title: Telling an std::thread to kill/stop itself when a condition is met
body: <p>Say I have a worker thread <code>tWorker</code>, which is initialized when <code>Boss</code> is constructed and tells it to do <code>work()</code>, until <code>bRetired</code> is true. An <code>std::mutex</code>, <code>mtx</code>, locks some data (<code>vFiles</code>) so that <code>tWorker</code> owns it when he's working on it.</p>
  
  <p>How do I make <code>tWorker</code> "commit suicide" once <code>bRetired</code> becomes <code>true</code>? How would the <code>mutex</code> be destroyed when the thread stops execution?</p>
  
  <p>I've read that <code>std::thread</code> objects cannot be interrupted in any way. Does letting the thread do nothing (or calling <code>std::this_thread::yield()</code>) provide the same effect as killing the thread?</p>
  
  <pre><code>class Boss {
  private:
      std::thread tWorker;
      std::mutex mtx;
      bool bRetired;
      std::vector&lt; std::string &gt; vFiles;
  
      void work() {
          while ( bRetired == false ) {
              // Do your job!
              mtx.lock();
              // ... Do something about vFiles ...
              mtx.unlock();
          }
  
          // tWorker has retired, commit suicide
          // ** How? **
  
          // Does this suffice if I want to "kill" the thread?
          std::this_thread::yield(); 
      }
  
  public:
      Boss() {
          bRetired = false;
          tWorker = std::thread( &amp;Boss::work, this );
  
          // Have worker do its job independently
          // **Bonus Question** : Should this be tWorker.join() or tWorker.detach()?
          tWorker.detach();
      }
  
      retire() {
          bRetired = true;
      }
  }
  </code></pre>
  
  <p><strong>Notes</strong></p>
  
  <ul>
  <li>The worker thread cannot be started again once it is retired.</li>
  <li>The worker thread works on the background without interrupting the main thread's execution.</li>
  </ul>