Tuesday, September 1, 2009

Qt and Threads

Multithreaded programming is fun, isn't it?

I'm writing a thin Qt wrapper around OpenAMQ so that we can encapsulate a connection in a separate thread without blocking the event loop in the main application thread.

Some guys at work have developed a few nifty tricks to make threaded programming in Qt easy... well, easier... actually, much easier.  But, I was still having some problems (which were mainly caused by some weirdness and wrong documentation in the OpenAMQ client library, but that's a different story).

Other than better understanding how QCoreApplication and QThread event loops interact, here's a lesson I learned:

Don't call deleteLater() within a class that inherits from QThread.  Reason being is that you need to call quit() before the QThread object is deleted, and once you do that, the event loop in QThread stops.  Since your event loop in the QThread object has stopped, the deleteLater will never get processed.

This all comes down to: using deleteLater in this scenario will never call your destructor.

Lesson learned.  Check.