title: QRunnable - how to implement WaitForFinished without a race?
body: <p>I have some I/O code in Qt that was moved to a <code>QRunnable</code> in order to avoid blocking the UI thread. This calls back with some queued slots to indicate its progress. </p>
  
  <p>However I recently saw some issues where when the owner of the <code>QRunnable</code> is destroyed it can't delete the runnable until its complete (otherwise crash as the worker thread is still using it). To solve this I'd like to add a "<code>WaitForFinished</code>" to the runnable that it will call its in dtor so I can simply delete the <code>QRunnable</code> and know that it will block until its done before its dtor exits.</p>
  
  <p>I thought this should be easy as all I need to do is use a <code>QMutex</code> in <code>QRunnable::run</code> implementation, then also acquire that mutex within <code>WaitForFinished</code>. However this has a race condition that I'm not sure how to solve.</p>
  
  <p>Consider the following:</p>
  
  <ol>
  <li><code>QRunnable</code> is queued to be executed.</li>
  <li><code>QRunnable</code> starts to execute but <code>QRunnable::run</code> has not yet been called</li>
  <li>The main thread deletes the <code>QRunnable</code> which calls <code>WaitForFinished</code> in the dtor and acquires the <code>QMutex</code> before <code>QRunnable::run</code> - so we assume its not running or finished running and destruct the <code>QRunnable</code>, but it hasn't even started yet!</li>
  </ol>