title: Proper way to stop a thread from a destructor
body: <p>I have a class that has a <code>Start</code> method to start a thread that executes the virtual <code>ThreadFunction</code> at a predefined interval. The <code>Stop</code> method sets an event and waits until the the thread terminates (by a <code>WaitForSingleObject</code> on the thread handle).</p>
  
  <p>In the destructor of <code>MyThread</code>, I call the <code>Stop</code> method. So whenever I delete the instance, I'm sure the thread is stopped before the delete returns.</p>
  
  <pre><code>class MyThread
  {
      void Start();
      void Stop();
      ~MyThread() { Stop(); }
      virtual VOID ThreadFunction() { }
  };
  </code></pre>
  
  <p>Next I have a class that derives from <code>MyThread</code>:</p>
  
  <pre><code>class A : MyThread
  {
      virtual VOID ThreadFunction()
      {
          for (int i = 0; i &lt; 1000; i++)
              TestFunction();
      }
  
      void TestFunction() { // Do something }
  };
  </code></pre>
  
  <p>Consider this code:</p>
  
  <pre><code>A a = new A();
  a-&gt;Start();
  delete a;
  </code></pre>
  
  <p>The problem is that <code>delete a</code> will first call the destructor of <code>A</code> before it will call the destructor of <code>MyThread</code> right? So if the thread was executing the <code>for-loop</code> in the <code>ThreadFunction</code>, the <code>Stop</code> method will be called after <code>a</code> has been destructed. This can lead to an access violation, when <code>ThreadFunction</code> calls <code>TestFunction</code> on a destructed instance.</p>
  
  <p>A solution would be to add a destructor to <code>class A</code> that calls the <code>Stop</code> method, like this:</p>
  
  <pre><code>class A : MyThread
  {
      ~A()
     {
         Stop();
     }
  }
  </code></pre>
  
  <p>But because I have a more complex class hiërarchy, that involves multiple inherited classes, this would mean I have to call the <code>Stop</code> method in each destructor, which would result in the Stop method being called plenty of times for only one instance that needs to be deleted.</p>
  
  <p>Is there any other way to tackle this problem?</p>