[Qt-interest] Immortal Programs!

Oliver.Knoll at comit.ch Oliver.Knoll at comit.ch
Thu Jul 2 10:48:01 CEST 2009


Gary Coulbourne wrote on Thursday, July 02, 2009 12:10 AM:

> ...
> I cannot find anything in the documentation to explain this
> behaviour, 

That's all about multithreaded programming, how to properly terminate threads when your app needs to terminate. Qt docs (http://doc.qtsoftware.com/4.5/threads.html) merely gives some general hints and pointers about this subject, but it can't replace a good book (http://doc.qtsoftware.com/4.5/threads.html#recommended-reading) or tutorial about concurrent programming.

> and was wondering if anyone else had some suggestions?

That's easy: terminate the thread (or all threads) that is processing data in the background, when exiting your application :)

Do it "graceful" by setting some "terminate" condition in the thread ("hint").

E.g. when your worker thread looks like this:

  private bool doContinue;
  private bool isDataCompletelyProcessed;
  ...
  void YourWorkerThread::doStart() {
    ...
    doContinue = true;
    while (doContinue == true) {
      Data data = waitForData(timeout);
      ProcessedData *processedData;
      // do process data in chunks, as to keep your thread responsive
      isDataCompletelyProcessed = false;
      while (doContinue == true && isDataCompletelyProcessed == false) {
        // processChunk should not take longer than e.g. 5 seconds, as to
        // keep thread responsive to doContinue "hints"
        isDataCompletelyProcessed = processChunk(data, processedData);
        ...
      }
    }
  }

  void YourWorkerThread::interrupt() {
    doContinue = false;
  }


Then before you exit your application (e.g. in the slot which is called when the last window closes) you would simply call:

  private const int I_AM_GETTING_IMPATIENT_TIMEOUT = 10000; // 10 seconds

  void YourApp::handleLastWindowClosed() {
    ...
    yourWorkerThread = ThreadManager::getWorkerThread(); // or wherever you keep track of your current threads
    // give your worker thread a "hint" to stop working
    yourWorkerThread->interrupt();
    // you STILL have to wait until your thread REALLY has terminated
    yourWorkerThread->wait(I_AM_GETTING_IMPATIENT_TIMEOUT);
    ...
  }

The "not so graceful and cruel" method is to simply "kill" your thread (with the possibility of corrupted data etc., in case your thread stores processed data to disk etc.)

  yourWorkerThread->terminate();
  yourWorkerThread->wait(I_AM_GETTING_IMPATIENT_TIMEOUT);

This is so brutal and cruel (and highly not recommended, see http://doc.qtsoftware.com/4.5/qthread.html#terminate) that I did not even mention this possibility ;)

Cheers, Oliver
   
p.s. Sorry if I have mixed up Java and C++ declarations above: look at it as "pseudo-code which gives you the general idea" ;)
-- 
Oliver Knoll
Dipl. Informatik-Ing. ETH
COMIT AG - ++41 79 520 95 22



More information about the Qt-interest-old mailing list