title: How to stop threads in Qt
body: <p>What is the corrent way to stop threads in Qt?</p>
  
  <p>Suppose that I have a worker (<code>LicenseChecker</code> class) and I want to do some actions every n seconds in the <code>process</code> member function. I need to do it indefinitely, until someone abort my loop.</p>
  
  <pre><code>_worker = new LicenseChecker;
  _thread = new QThread;
  _worker-&gt;moveToThread(_thread);
  
  connect(_thread, SIGNAL(started()), _worker, SLOT(process()));
  connect(_worker, SIGNAL(finished()), _thread, SLOT(quit()));
  connect(_worker, SIGNAL(finished()), _worker, SLOT(deleteLater()));
  connect(_thread, SIGNAL(finished()), _thread, SLOT(deleteLater()));
  connect(_worker, SIGNAL(newLicensesActivated(QVector&lt;LicenseInfo&gt;)),
                   this, SLOT(newLicensesActivated(QVector&lt;LicenseInfo&gt;)));
  
  _thread-&gt;start();
  </code></pre>
  
  <p>What can I do to abort it?</p>
  
  <p>The first idea that I came up with was to define the <code>sleep</code> function as the following:</p>
  
  <pre><code>bool LicenseChecker::sleep(int seconds)
  {
      QTime end_time = QTime::currentTime().addSecs(seconds);
      while (QTime::currentTime() &lt; end_time)
      {
          QCoreApplication::processEvents(QEventLoop::AllEvents, 100);
  
          QMutexLocker lock(&amp;_abort_sync);
          if (_abort)
          {
              return false;
          }
      }
  
      return true;
  }
  </code></pre>
  
  <p>and to check the return code of this function in my infinite loop:</p>
  
  <pre><code>while (true)
  {
      if (!sleep(5))
      {
          emit finished();
          return;
      }
  
      // ...
  }
  </code></pre>
  
  <p>And then on <code>MainWindow</code>'s close event I need to do the following:</p>
  
  <pre><code>_worker-&gt;stop();
  _thread-&gt;wait();
  </code></pre>
  
  <p>where <code>stop</code> member function just sets <code>_abort</code> data member to <code>true</code>, but the application hangs on these calls.</p>
  
  <p>What is the right way to accomplish such task?</p>