title: Qt concurrent threads: QFuture::cancel() and "pair" QFuture::waitForFinished()
body: <p>I am using Qt5 on Windows7.<br>
  In my current app I have a class <code>Connector</code> that I use to connect to some remote databases.<br>
  To implement that I decided to use <code>QtConcurrent::map</code> in order to achieve better speed.<br>
  So far ok, but I had some issues when trying to quit the app with active connections (running threads). Obviously, I had to cancel them or wait for them to finish, in order to exit the app gracefully.<br>
  First step, I tried something like this :    </p>
  
  <pre><code>void Connector::cancelProcessing()   
  {   
     future.cancel();   
     future.waitForFinished();   
  }   
  </code></pre>
  
  <p>Well, it works, but it has the major disadvantage that it freezes the GUI.<br>
  So, I decided to move forward to next step :<br>
  I implemented a <code>WaitDialog</code> that is called when I exit my app (just to show something to user).<br>
  As a picture says more than 1000 words, well... it looks like that:<br>
  <a href="https://i.stack.imgur.com/DG3pY.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DG3pY.jpg" alt="enter image description here"></a>   </p>
  
  <p>Nothing complicated, it just waits for the <code>finished()</code> signal (from the future watcher of the concurrent processing).<br>
  <code>Close</code> push-button foreseen just in case app goes bananas.<br>
  I modified the code above: as <code>waitForFinished</code> renders <code>WaitDialog</code> useless, I removed it:   </p>
  
  <pre><code>void Connector::cancelProcessing()   
  {   
     future.cancel();   
     //future.waitForFinished(); &lt;- removed, so we can see the wait-dialog!  
  }   
  </code></pre>
  
  <p>Well, in this case the app crashes horribly at exit :(<br>
  I know there's no more <code>finished()</code> signal emitted (due to calling <code>cancel()</code>), but even so... Even if I wait 10, 30 or 60, etc seconds before pressing <code>Close</code> button, the app still crashes. <strong>Why</strong>?!    </p>
  
  <p>I found some workaround for this problem: I'm just using some cooperative-canceling instead, i.e. a variable <code>bool forceQuit</code> inside <code>Connector</code> class, that gets  set - <em>and then tested by threads</em> - when I want to exit app and terminate all threads. Seems trivial, but pfff... <strong>What else</strong>? :(   </p>
  
  <p>Anyway, I still have 2 question about the above described problem:<br>
  <strong>1)</strong> <code>QFuture::cancel()</code> and <code>QFuture::waitForFinished()</code> must always be used in tandem/pair? Without <code>QFuture::waitForFinished()</code> the app crashes, probably some objects are going <code>out of scope</code> or what?<br>
  <strong>2)</strong> Is there any other idea/solution to solve the above issue, <em>other than the cooperative-cancelling</em>?     </p>
  
  <p>Thanks for your time and patience!</p>