title: Best way to handle multi-thread cleanup
body: <p>I have a server-type application, and I have an issue with making sure thread's aren't deleted before they complete. The code below pretty much represents my server; the cleanup is required to prevent a build up of dead threads in the list.</p>
  
  <pre><code>using namespace std;
  
  class A {
  public:
      void doSomethingThreaded(function&lt;void()&gt; cleanupFunction, function&lt;bool()&gt; getStopFlag) {
         somethingThread = thread([cleanupFunction, getStopFlag, this]() {
            doSomething(getStopFlag);
            cleanupFunction();
         });
  
      }
  private:
      void doSomething(function&lt;bool()&gt; getStopFlag);
      thread somethingThread;
      ...
  }
  
  class B {
  public:
      void runServer();
  
      void stop() {
          stopFlag = true;
          waitForListToBeEmpty();
      }
  private:
      void waitForListToBeEmpty() { ... };
      void handleAccept(...) {
          shared_ptr&lt;A&gt; newClient(new A());
          { 
              unique_lock&lt;mutex&gt; lock(listMutex);
              clientData.push_back(newClient);
          }
          newClient.doSomethingThreaded(bind(&amp;B::cleanup, this, newClient), [this]() {
              return stopFlag;
          });
      }
  
      void cleanup(shared_ptr&lt;A&gt; data) {
          unique_lock&lt;mutex&gt; lock(listMutex);
          clientData.remove(data);
      }
  
      list&lt;shared_ptr&lt;A&gt;&gt; clientData;
      mutex listMutex;
      atomc&lt;bool&gt; stopFlag;
  }
  </code></pre>
  
  <p>The issue seems to be that the destructors run in the wrong order - i.e. the shared_ptr is destructed at when the thread's function completes, meaning the 'A' object is deleted before thread completion, causing havok when the thread's destructor is called.</p>
  
  <p>i.e.
  Call cleanup function
  All references to this (i.e. an A object) removed, so call destructor (including this thread's destructor)
  Call this thread's destructor again -- OH NOES!</p>
  
  <p>I've looked at alternatives, such as maintaining a 'to be removed' list which is periodically used to clean the primary list by another thread, or using a time-delayed deletor function for the shared pointers, but both of these seem abit chunky and could have race conditions.</p>
  
  <p>Anyone know of a good way to do this? I can't see an easy way of refactoring it to work ok.</p>