title: How do I wait for a thread to finish in Qt without blocking its execution?
body: <p>I have a function that creates a bunch of QThreads to speed up a long calculation, but when I try and sleep until the calculation is done, the background threads never execute for some reason. </p>
  
  <p>I can't figure out why the threads don't execute after I call <code>thread-&gt;start()</code>. Here's my code:</p>
  
  <pre><code>multithread.run_multithread(run_function, thread_count);
  while(multithread.running)
      QThread::msleep(100);
  qDebug() &lt;&lt; "done";  // Never reaches this point
  </code></pre>
  
  <p>And the multithread function:</p>
  
  <pre><code>void Multithread::run_multithread(std::function&lt;void
   (int)&gt;run_function_in, int thread_count) {
      running = true;
      // Create workers and threads
      int thread_idx;
      for(thread_idx=0; thread_idx&lt;thread_count; thread_idx++) {
          ThreadWorker *worker = new ThreadWorker(this, run_function_in);
          QThread *thread = new QThread();
          // Set workers and threads to delete when done
          worker-&gt;moveToThread(thread);
          connect(worker, &amp;ThreadWorker::finished, this, &amp;Multithread::check_progress);
          connect(thread, &amp;QThread::started, worker, &amp;ThreadWorker::run);
          connect(worker, &amp;ThreadWorker::finished, thread, &amp;QThread::quit);
          connect(worker, &amp;ThreadWorker::finished, worker, &amp;ThreadWorker::deleteLater);
          connect(thread, &amp;QThread::finished, thread, &amp;QThread::deleteLater);
          // Start thread
          thread-&gt;start();
      }
  }
  </code></pre>
  
  <p><code>running</code> gets set to <code>false</code> in <code>Multithread::check_progress</code> when all the threads finish their part of the calculation. When I remove <code>QThread::msleep(100)</code> the calculation will execute normally, but I need some way to block until it completes.</p>