You’re doing it wrong…

Published Thursday June 17th, 2010 | by

We use IRC extensively to communicate amongst ourselves as well as with the community. I hang out on the #qt channel on the Freenode network and help people with questions when I can. A common question that I see (and that makes me cringe at the same time) has to do with understanding threading with Qt and how to make some code they’ve written work. People show their code, or examples based on their code, and I often end up thinking:

You’re doing it wrong


I know this is a bit of a bold thing to say, perhaps a bit provocative, but at the same time, I can’t help but think that the (hypothetical) class below is an incorrect application of object-oriented principles as well as incorrect usage of Qt.

class MyThread : public QThread
{
public:
    MyThread()
    {
        moveToThread(this);
    }

    void run();

signals:
    void progress(int);
    void dataReady(QByteArray);

public slots:
    void doWork();
    void timeoutHandler();
};

My #1 biggest gripe with this code is moveToThread(this); I see so many people using this without understanding what it does. What does it do, you ask? The moveToThread() function tells Qt to ensure that event handlers, and by extension signals and slots, are called from the specified thread context. QThread is the thread interface, so we’re telling the thread to run code “in itself”. We’re also doing this before the thread is running as well. Even though this seems to work, it’s confusing, and not how QThread was designed to be used (all of the functions in QThread were written and intended to be called from the creating thread, not the thread that QThread starts).

My impression is that moveToThread(this); creeps into people’s code because they saw some blog somewhere that used it. A quick web search turns up several of these blogs, all of which follow the pattern in the class above:

  1. subclass QThread
  2. add signals and slots to do work
  3. test code, see that the slots aren’t called “from the right thread”
  4. ask google, find moveToThread(this); and comments that “it seems to work when I add this”

In my opinion, the problems started at step 1. QThread was designed and is intended to be used as an interface or a control point to an operating system thread, not as a place to put code that you want to run in a thread. We object-oriented programmers subclass because we want to extend or specialize the base class functionality. The only valid reasons I can think of for subclassing QThread is to add functionality that QThread doesn’t have, e.g. perhaps providing a pointer to memory to use as the thread’s stack, or possibly adding real-time interfaces/support. Code to download a file, or to query a database, or to do any other kind of processing should not be added to a subclass of QThread; it should be encapsulated in an object of it’s own.

Usually, this means simply changing your class to inherit from QObject instead of QThread and, possibly, changing the class name. QThread has a started() signal that you can connect to when you need to perform some initialization. To actually have your code run in the new thread context, you need to instantiate a QThread and assign your object to that thread using the moveToThread() function. Even though you are still using moveToThread() to tell Qt to run your code in a specific thread context, we are keeping the thread interface separate. If necessary, it is now possible to have multiple instances of your class assigned to a single thread, or multiple instances of many different classes assigned to a single thread. In other words, it’s unnecessary to tie a single instance of a class to a single thread.

I take much of the blame for the confusion that comes with writing threaded Qt code. The original QThread class was abstract, so subclassing was necessary. It wasn’t until Qt 4.4 that QThread::run() gained a default implementation. Previously, the only way to use QThread was to subclass. With the addition of thread affinity and support for signal and slot connections between objects of different affinity, suddenly we have a convenient way of working with threads. We like convenience, we want to use it. Unfortunately, I realized to late that forcing people to subclass QThread actually made it harder than it needed to be.

I also take the blame for not getting up-to-date examples and documentation made to show people how to get the convenience with the minimum amount of headaches. For now, the best resource I can point at is
a blog I wrote several years ago.

Disclaimer: everything you see above is of course opinion. I’ve worked a lot on these classes, and have a fairly clear idea of how to use them and how not to use them.

Did you like this? Share it:
Bookmark and Share

Posted in Uncategorized

79 comments to You’re doing it wrong…

Palmik says:

Great article, it should clear some things up :)

Will Stokes says:

Very interesting. I suspect I’m not using threads are intelligently as I could just yet then. I currently subclass QThread, give it a queue of jobs (private variable), then pop off the jobs and process them in the run function. I start the thread with start obviously. I’d appreciate an updated example of how QThread should be used today without subclassing since the link you posted to refers to QThread back when you still had to re implement the run method…

s1n says:

I think you should cut your users some slack. This is directly from the documentation:

A QThread represents a separate thread of control within the program; it shares data with all the other threads within the process but executes independently in the way that a separate program does on a multitasking operating system. Instead of starting in main(), QThreads begin executing in run(). By default, run() starts the event loop by calling exec() (see below). To create your own threads, subclass QThread and reimplement run(). For example:

It continues from there. If users are not supposed to subclass QThread, then the documentation needs updating. You can’t fault users for following your documentation and then mindlessly using code they see on the internet because your documentation is incorrect.

Adam says:

I can’t tell you how many times I’ve tried to tell people that moveToThread(this); is not the magic answer to thread problems. Now all you need to do is get this post to the top of google (and have people point to it on stackoverflow.com)

Tim says:

Can you post a code example of how to ‘do it right’?

franzk says:

Tim: check out the blog he wrote several years ago. It does basically what Bradley wrote in the post.

Kirk Bateman says:

Worth noting that the online documentation for qt 4.6 still says to create a thread you must subclass QThread.

http://doc.qt.nokia.com/4.6/threads-starting.html

Medalin Murgoliga says:

As of Oct. 22, 2012, the official Qt 4.8 Documentation tells:

“To create your own threads, subclass QThread and reimplement run().”

http://qt-project.org/doc/qt-4.8/qthread.html

razvanpetru says:

I like using QtConcurrent::run. Since it uses the thread pool, it should queue tasks automatically too. :)

jackieku says:

The examples allocate the Producer and Consumer objects on the stack. But what if you instance the object by “new”?

1.
QThread workerThread;
Worker *worker = new Worker(this);
worker->moveToThread(&workerThread); // !! failed because “worker” has a parent

2.
QThread workerThread;
Worker *worker = new Worker;
worker->moveToThread(&workerThread);
worker->setParent(…); // !! can not be called in this thread context

3.
QThread workerThread;
Worker *worker = new Worker;
worker->setParent(&workerThread);
worker->moveToThread(&workerThread); // !! same with 1

So in either case you need to track the lifetime of “worker” by yourself. Yes, we can do it. But I think it is a bit cumbersome.

scorp1us says:

I am even more confused now. I’ve been using QThread, never used moveToThread() nd always just override run() with the functionality. I’ve done processing and signals/slots. Everything works fine. Are you saying I’m doing somethign wrong?

For me it has never mattered which thread does the signal/slot handling.
In your P&C example, I would have had each run() implementation emit produced(QByteArray) or consumed() and I never would have used moveToThread()

Now I am more confused than ever.

André Fillipe says:

After reading this piece, my opinion now is that the documentation on threading-related stuff in Qt is a bit of a mess. It never occurred to me that this is the intended usage of QThread because all the threading examples do subclass QThread. Furthermore, the part of the documentation about how Qt::AutoConnection is resolved in multi-threading situations is still just plain wrong as of Qt 4.6.3 (http://lists.trolltech.com/pipermail/qt-interest/2010-May/023514.html).

So, we’re doing it wrong because we’ve been told by you to do it wrong (or at least not how to do it right).

Thanks for this clarification, though! Now that I understand how QThread is intended to be used, I begin to appreciate the design of it all.

detro says:

Well, I see your point, and it clarifies finally why QThread is done in this way.
Indeed, when we tried to do complex stuff with QThread, assuming that QThread should be subclassed in the way you described, stuffed looked pretty weird.

One reason for me is the comparing with stuff like the Common C++ 2 library (that I used in the *remote* past) and Java Threads (that I used in the past). There you subclass a Thread, implement a method that will contain your “threaded code”, and run it.

In QThread stuff are totally different, and, honest, I’m not really sure I agree that “it’s better this way”.

As Tim said, would be nice to see HOW the right way looks like. Just to get an even better understanding of what you mean.

Michael says:

I guess most of the “incorrect application of object-oriented principles as well as incorrect usage of Qt” is caused by the QThread documentation itself, which states:
[cite]
… To create your own threads, subclass QThread and reimplement run(). For example:

class MyThread : public QThread
{
public:
void run();
};

void MyThread::run()
{
QTcpSocket socket;
// connect QTcpSocket’s signals somewhere meaningful

socket.connectToHost(hostName, portNumber);
exec();
}
[cite]

Nice to see how one actually should do it…

Lulzfish says:

I usually just try to follow the documentation:
http://doc.qt.nokia.com/4.6/qthread.html#details

Which seems to recommend subclassing as the default way to make things happen in a separate thread.
But instead, I need to subclass QObject, then move that to a thread? Interesting.

Matthew says:

I’m with Tim on this one… It would be nice to see an example of how you would run your code in a thread. Other goodies like properly reporting progress and thread termination would be interesting too. You explanation is good but I think if 5 different people were to read your explanation you’d probably see 5 different implementations

Luca says:

Very useful point of view… Thanks!

David says:

You say that one really does not (often) need to subclass QThread. But doesn’t the value of a thread lie in its run method. I would think more often then not you are going to want to implement your own version of run();

TemporalBeing says:

Very interesting, and I think it’s probably one of the best explanations on how to 100% properly use QThread.

NuShrike says:

I’m not seeing how creating a QObject-subclass and moving it to a QThread is more advantageous and less code/object-oriented than instantiating the QThread subclass, and it opaquely manages its own thread state as inherited. Personally never used moveToThread() as its existence is bewildering.

I professionally develop a real-time video player in OpenGL with Qt. This video player has to be interrupt-driven to be frame-accurate so it never misses a frame and isn’t held-hostage by the Qt GUI thread. Of course this has been difficult because the Qt GUI system (QGraphicsView and QObject) is so anti-thread, insists on being event driven, and the Qt signals-slots can’t be trusted to be real-time for simple signals. I use semaphores, direct function calls, or Boost signals instead.

This has meant I’d subclass QThread to represent a “pump” worker-thread with internal nearly-lockless producer/consumer circular queue for images/commands to process. Specific singleton pumps are dedicated as the “manager” thread for its job — which can sub-multithread out further such as image-to-texture conversion, and texture uploading. There’s even a custom multi-core (because the threads stay resident) memcpy class based off the pump. Of course “pump” sounds like the standard event-queue except it’s directly waitable (or not), and supports reading/writing to it at the same time.

I’ve looked at QtConcurrent (and found it slower) as well as QFutures because of the overhead in thread-creation/destruction by not staying resident. QThreadPool has a primitive API incomparable to QtConcurrent and can’t deal with my design requirements. It’s being “fun” to get QGraphicsScene to work with being shared between the GUI and renderer thread because all QObject-based (multi-thread incompatible) policy-classes have to be reimplemented such as QGraphicsLinearLayout.

BTW, I hope the upcoming QGLObject class isn’t based on QObject as QGLShaderProgram is because it’s multi-thread incompatible with context-shared OpenGL. I have custom template-based “GLObject” classes which are fully multi-context compatible and practically no real-code overhead vs Qt’s MFC-like bloat, so I’ll probably never use QGLObject.

It was already quite a shock with QGLShaderProgram to find it thread-locked and imo wastefully checking the GLContext all the time. QGLFrameBufferObject has the same issues. Qt should get out of the way on this and let OGL manage object sharing and context appropriateness (or move the guard code into Loki-like typelists that compiles away), and only provide useful error handling/tracking when it’s not a speed hit to read them from OGL. Checking errors itself is a read-back that stalls the GL pipeline and shouldn’t be used in release code.

Using Qt has been great and I fully appreciate the work of all contributors and LGPL, but I do like to see some of Qt evolve into something more simultaneous-multi-thread compatible.

Once I managed to get the change in to make QThread::run() have a default implementation, I wrote another blog, with an updated example: http://labs.trolltech.com/blogs/2007/07/05/qthreads-no-longer-abstract/

However, like I mentioned, the existing docs and examples are pretty lacking. I have some snippets here and there that I plan on pulling together to make some more examples that show more than the producer-consumer pingpong that is linked in the previous blogs. (Yes, even though the examples use threads, they aren’t concurrently producing and consuming… more complex examples are needed, obviously).

Thanks for the feedback, I’ve been wanting to get this off my chest for a while (as well as getting the motivation to actually DO something about the docs and examples). Watch this space… :P

ath0 says:

Well you can’t be really surprised people are doing it “wrong”: “To create your own threads, subclass QThread and reimplement run().” -from the Qt 4.6.3 help docs

Leo S says:

Hmm, yeah I think saying that the official approach from the documentation is suddenly wrong is a bit much.
I can see that you can gain additional features by not subclassing QThread, but I’ve never needed those features in my programs, so I don’t see any point in rewriting code, or even writing new code differently. The subclassing approach works just fine (with the moveToThread of course).

Fazer says:

It’s funny that I learned the hack with “moveToThread(this) in ctor” on the #qt channel itself…Now that you described the recommended way to use QThread, it does make more sense to me.

mcattell says:

I created an example a few months ago, using the good advice of Mr. Hughes. After reading this and seeing that folks wanted to see demonstration code, I decided to upload it to gitorious. It’s a multi-threaded client-server test application that simply pushes blocks of test data from multiple clients to a multi-threaded server. Although it’s not the most exciting of applications, it demonstrates how the GUI remains responsive even with multiple connections and large amounts of I/O activity in the background. You can find the example code here:- http://gitorious.org/qthreadhowto/qthreadhowto

Comments and feedback always welcome.

Stefan says:

Has anyone tried to use QWebPage in a multithreaded way? I can find some other people in forums that also have trouble getting this to work.

Jeremy says:

There is a massive hole in the documentation. I Googled for “QThread moveToThread” hoping to find some example code, and found zero results. The Mandelbrot example also shows how to subclass QThread, extending both the ctor and run(). I’ve only recently started learning Qt, and I’m surprised that the only documentation for how to actually use this particular api is in a tarball (not searchable) posted over three years ago. My experience with Qt has been mostly positive, but it’s possible that you’re doing documentation wrong.

stephenju says:

Thanks for the great write up. I wish this information is in QThread doc. Would have saved me a lot of time. :)

Philippe says:

Not recommanded to sub-class? Then, to be coherent, transform the 4 QThread “Static Protected Members” to “Public Protected Members”… a suggestion that was always rejected so far…

AC says:

If the first example of the QThread documentation is “Doing it Wrong” then I would suggest changing your Wrong documentation instead of writing a blog post mocking everyone who follows the documentation.

Kari says:

So, the conclusion is:
1. Don’t read Qt 4.6 docs, it is wrong as it says “To create your own threads, subclass QThread and reimplement run().” http://doc.qt.nokia.com/4.6/qthread.html#details

2. Don’t read the given “best resource”, it is also wrong, because it also subclasses QThread: “…just a small amount of work: subclass QThread and reimplement run()..” http://labs.trolltech.com/blogs/2006/12/04/threading-without-the-headache/

The correct answer is in the shortest blog given in the comments: http://labs.trolltech.com/blogs/2007/07/05/qthreads-no-longer-abstract/
Here’s a shortened snippet from it for those who don’t want to dig into the tarball:

class Producer : public QObject
{
Q_OBJECT
public slots:
void produce() { …emit produced(&data)…emit finished().. }
signals:
void produced(QByteArray *data);
void finished();
};

class Consumer : public QObject
{
Q_OBJECT
public slots:
void consume(QByteArray *data) { …emit consumed()…emit finished().. }
signals:
void consumed();
void finished();
};

int main(int argc, char **argv)
{
QCoreApplication app(argc, argv);
// create the producer and consumer and plug them together
Producer producer;
Consumer consumer;
producer.connect(&consumer, SIGNAL(consumed()), SLOT(produce()));
consumer.connect(&producer, SIGNAL(produced(QByteArray *)), SLOT(consume(QByteArray *)));

// they both get their own thread
QThread producerThread;
producer.moveToThread(&producerThread);
QThread consumerThread;
consumer.moveToThread(&consumerThread);

// start producing once the producer’s thread has started
producer.connect(&producerThread, SIGNAL(started()), SLOT(produce()));

// when the consumer is done, it stops its thread
consumerThread.connect(&consumer, SIGNAL(finished()), SLOT(quit()));
// when consumerThread is done, it stops the producerThread
producerThread.connect(&consumerThread, SIGNAL(finished()), SLOT(quit()));
// when producerThread is done, it quits the application
app.connect(&producerThread, SIGNAL(finished()), SLOT(quit()));

// go!
producerThread.start();
consumerThread.start();
return app.exec();
}

Rick says:

I personally don’t understand why *sleep static methods are protected as a previous poster possibly mentioned. In fact you need those methods even if you develop a single threaded application. Weird…

sroedal says:

Using sleep is typically a sign of bad design. With a proper event loop there should be no need to make the thread sleep for an arbitrary amount of time.

Rick says:

sroedal: You’re right, they can easily be abused by incompetent programmers but on some occasions it’s much simpler to call msleep instead of installing a QTimer e.g. when you’re driving a remote hardware over serial bus.

Kejk says:

Thanks for this article, unfortunaly it is too late for me – I’ve done some work few months ago (with many problems) using the way you discourage. Project is critical for me and is too late to rewrite it. :(

Marc Espie says:

It’s an artifact of the way people learn OO programming.

All courses spend a lot of time explaining inheritance, making it look sexy.

In real code, inheritance is a plague. You’re ways more concerned about encapsulation and proper isolation.

Granted, beginners should probably be forbidden to use inheritance, unless someone more experienced can tell them that specific class WAS designed for inheritance.

C++ makes it even harder thanks to private inheritance… choices, choices, choices ! All those ways to write code that “works”, but using a bogus design that will bite your ass HARD later on, and take a really big chunk out of it if you’re not real lucky….

As a designer, writing abstract classes is very tricky. You have to write extensive documentation, otherwise people will misuse it. The initial misdesign of QThread, and the subsequent lack of publicity on the fixed design are a test book example of how NOT to do things if you don’t want beginners to misuse it…

NuShrike says:

I’m not seeing how creating a QObject-subclass and moving it to a QThread is more advantageous and less code/object-oriented than instantiating the QThread subclass, and it opaquely manages its own thread state as inherited. Personally never used moveToThread() as its existence is bewildering.

Users should always be given access to sleep() because you can’t dictate what their actual needs are, esp when it comes to hardware, or interrupt driven code. Because Qt doesn’t do this, we have our own multi-platform wrappers for usleep, msleep, and sleep.

I professionally develop a real-time video player in OpenGL with Qt. This video player has to be interrupt-driven to be frame-accurate so it never misses a frame and isn’t held-hostage by the Qt GUI thread. Of course this has been difficult because the Qt GUI system (QGraphicsView and QObject) is so anti-thread, insists on being event driven, and the Qt signals-slots can’t be trusted to be real-time for simple signals. I use semaphores, direct function calls, or Boost signals instead.

This has meant I’d subclass QThread to represent a “pump” worker-thread with internal nearly-lockless producer/consumer circular queue for images/commands to process. Specific singleton pumps are dedicated as the “manager” thread for its job — which can sub-multithread out further such as image-to-texture conversion, and texture uploading. There’s even a custom multi-core (because the threads stay resident) memcpy class based off the pump. Of course “pump” sounds like the standard event-queue except it’s directly waitable (or not), and supports reading/writing to it at the same time.

I’ve looked at QtConcurrent (and found it slower) as well as QFutures because of the overhead in thread-creation/destruction by not staying resident. QThreadPool has a primitive API incomparable to QtConcurrent and can’t deal with my design requirements. It’s being “fun” to get QGraphicsScene to work with being shared between the GUI and renderer thread because all QObject-based (multi-thread incompatible) policy-classes have to be reimplemented such as QGraphicsLinearLayout.

BTW, I hope the upcoming QGLObject class isn’t based on QObject as QGLShaderProgram is because it’s multi-thread incompatible with context-shared OpenGL. I have custom template-based “GLObject” classes which are fully multi-context compatible and practically no real-code overhead vs Qt’s MFC-like bloat, so I’ll probably never use QGLObject.

It was already quite a shock with QGLShaderProgram to find it thread-locked and imo wastefully checking the GLContext all the time. QGLFrameBufferObject has the same issues. Qt should get out of the way on this and let OGL manage object sharing and context appropriateness (or move the guard code into Loki-like typelists that compiles away), and only provide useful error handling/tracking when it’s not a speed hit to read them from OGL. Checking errors itself is a read-back that stalls the GL pipeline and shouldn’t be used in release code.

Using Qt has been great and I fully appreciate the work of all contributors and LGPL, but I do like to see some of Qt evolve into something more simultaneous-multi-thread compatible.

Tom says:

I must confess I’m confused now. Does this mean all Qt Doc about QThreads is outdated?
Well, is it save to call QCoreApplication::processEvents() instead using QTimer in a QThread?

dude says:

Mind giving us an example of what “to do” rather than what “not to do” ?

Rupert Finklestein says:

Brad, were you a woman, I would have brute forced the equivalent of “Open Sesame” out of you, beautiful man.

Will Stokes says:

For the record I’m doing the exact same thing as scorp1us. I subclass QThread, reimplement the run method, and process data I store in private variables. I add public functions to the thread class to interact with it (e.g. schedule jobs), which is done by first getting a lock on a mutex for interacting with the data. I try to lock-unlock mutex’s as little as possible and for as short a time as possible. In some cases I have threads where jobs that come in can evict older jobs that are still in the queue. In such cases I can’t see how I could do what I do without subclassing QThread. So, I’d like to ask, why is the approach the Qt docs have advocated, and the one that I and scorp1us have been using, “wrong”? What is “wrong” about it? Since I’ve never used moveToThread (I don’t think I ever even noticed it before!) that there is nothing actually wrong about the approach I’ve always taken. I suspect there are different ways to accomplish the same thing, and recent changes in Qt mean for simpler threading contexts it’s possible to accomplish multi-threading without subclassing QThread.

MangoCat says:

Ironic, in our larger (multi-programmer) apps, we use a “RegisteredThread” subclass of QThread. RegisteredThreads respond to a shutdown signal so they can all be stopped gracefully before program exit, it’s a fairly simple layer:

RegisteredThread::RegisteredThread( const QString &name, QObject *parent ) : QThread( parent )
{ setObjectName( name );
initRegisteredThread( parent );
}

void RegisteredThread::initRegisteredThread( QObject *parent )
{ shutdownNow = false;
shutdownWhenReady = false;
connect( &threadRegistry, SIGNAL( shutdown( int ) ), SLOT( shutdown( int ) ) );
if ( !parent )
{ start();
moveToThread( this );
}
}

I just recently added that “moveToThread(this)” into the constructor code because, more often than not, it’s what the programmers want to do when they “create a new thread.”

If QThread is truly meant as a thread manager, it would seem more appropriate to roll it up in QApplication. Back in the “old days” having to declare a separate “worker object” to be instantiated within the subclassed “run()” just seemed like tail chasing. The present system still seems a little awkward no matter how you approach it, but if I subclass RegisteredThread and use the default constructor, then my new class’ slots are executed in the new thread without further coding. Wasn’t that the old motto?

Create more, code less.

Daniel says:

Agree with scorp1us and Will Stokes: never even noticed moveToThread before, but things work great with subclassing and signals/slots. If you are subclassing and have to blindly use moveToThread to “solve” your problem, then the real problem is that your code / design is screwed up. Don’t see how the new suggested architecture is going to magically solve things for people with those sorts of problems.

P.S. I hate that sleep is protected, it often comes in useful in quick-and-dirty test code and prototypes.

Philippe says:

Hack to bypass Qt protected sleep:

class QWrapperThread : public QThread
{
public:
static void Sleep(unsigned long msecs) { QThread::msleep(msecs); }
};

inline void qSleep(uint t) { QWrapperThread::Sleep(t); }

NuShrike says:

Funny how all my previous comments have been censored. Anyways, using moveToThread() imo is also a sign of bad design. Not allowing public usage of sleep() is so trivial in comparison.

aep says:

I take the blame for linking to half correct blog entries out of laziness. I wrote my own correct entry now, because i didn’t realize you already did. Next time just poke me, so we can correct the channels factoid ;)

Daniel Molkentin says:

@Philippe: This will fail on platforms where the compiler mangles the visibility into the symbol name, such as MSVC.

Philippe says:

@Daniel: really? This does work on both Visual C++ 2008 and latest XCode/GCC.

After all, this is strictly legal C++.

Harald Fernengel says:

@Daniel: The symbol is not renamed/removed, but simply called from a subclass. This works on all compilers. Philippe’s code is correct.

Wow, I go away for the weekend and come back to lots of good comments :P

To set the record straight: I’m not saying sub-classing QThread is wrong. This is also how Java does it (sort of), and many people have been doing this with Qt for a long time.

What I’m saying is “wrong” is subclassing QThread, adding signal and slot code to that subclass, and then calling moveToThread(this); in the constructor of that subclass. This causes people lots of confusion from my experience and observation on the #qt channel and the qt-interest mailing list.

And yes, the current docs are still a bit lacking, something that I am fully aware of (and take responsibility for). I’m planning on sitting down and fleshing them out, showing both ways of using QThread (with and without subclassing).

Danny says:

Every Qt book I’ve read (including the official one from Trolltech), the online Qt documentation and the course notes from KDAB specifically subclass from QThread and override run().

docman says:

Epic fail…

I thought Qt had a rockstar documentation dude on the team to deal with the docs, and the documentation part is something they’re proud of. I’m not so sure that the docs are their holy grail anymore. At least write in bold red letters “Example of how to misuse the Qthread” right next to the sample code so coders aren’t misguided.

Rick says:

I think there’s not a big deal here. As far as I understand the poblem is not inheriting from QThread. Actually in the past you had to do that. Problem is inheriting from QThread _and_ defining new slots _and_ expecting them to run in the context of this QThread. It doesn’t, so people use the moveToThread kludge. I personally never did that but appearently there are wrong examples on the Net so this provacative blog entry is written.

Now, stop acting like users of your library are dumb and give me my public sleep functions. Thank you :)

Roland Wolf says:

History:
Starting with Qt 4.4 QThread was not abstract anymore and QThread::run called exec(). This made it possible to instantiate a plain QThread and call the start() method which results in a new thread with an idling event loop. This means, Qt4.4 made it also possible to run a slot of any QObject derrived class in the context of the newly created thread by using QObject::moveToThread() and connect the slot to the started() signal of QThread.

Summary:
Subclassing QThread used to be the only way to create a thread with Qt till Qt 4.3
Subclassing QThread is still a good way to create a thread.
Subclassing QThread is still the only way to create a thread if no running event loop is wanted in the new thread.
QObject::moveToThread() can be used to let a slot run in the context of another thread. This needs additional plumbing however.

Guillaume Lachaud says:

Ok great article, I have always been in trouble with threads in Qt. So does this mean that this code is enough to get me rid of freezing interface while connecting to a database ?

BDDThread = new QThread();
database->moveToThread(BDDThread);
BDDThread->start();
database->open();

I have no warnings but the interface is still freezing (developping for Symbian on the Simulator).

Thanks for clearing things out, the documentation should be updated regarding this point

Daniel says:

Thanks to this I realized I was subclassing QThread incorrectly as my main thread (GUI) would block when it shouldn’t be. However trying to do it the “correct” way I found that my signals and slots no longer work.

I have in my MainWindow.h header:

public:
MyObject o; //subclass of QObject(parent =0)
QThread thread;

In my MainWindow.cpp constructor:

//setup connections between “this” (GUI widgets) and slots in “o”

o.moveToThread(thread);
o.start();

If I comment out “o.moveToThread(thread);” my signals/slots work. When I move MyObject o to QThread thread, they no longer work. Am I missing something obvious? (Q_OBJECT macro is obv. declared in MyObject since signals/slots work prior to moving to thread).

Daniel says:

Thanks to this I realized I was subclassing QThread incorrectly as my main thread (GUI) would block when it shouldn’t be. However trying to do it the “correct” way I found that my signals and slots no longer work.

I have in my MainWindow.h header:

public:
MyObject o; //subclass of QObject(parent =0)
QThread thread;

In my MainWindow.cpp constructor:

//setup connections between “this” (GUI widgets) and slots in “o”

o.moveToThread(&thread);
o.start();

If I comment out “o.moveToThread(&thread);” my signals/slots work. When I move MyObject o to QThread thread, they no longer work. Am I missing something obvious? (Q_OBJECT macro is obv. declared in MyObject since signals/slots work prior to moving to thread).

One of the problems I see with this, many times, there are objects that if they are not part of the parent/child chain all owned by they same thread, you get errors.

For example, QSqlDatasbase and QSqlQuery.

Normally, I take care of this, by my QThread NOT allocating any objects, till the RUN method, as opposed to initializing things in the constructor.

With this method, Im not sure when to do it..

aep says:

Since some people appear still to be confused how to do it *right*:

http://blog.exys.org/entries/2010/QThread_affinity.html

NuShrike says:

Famous words now if you link it to Steve Job’s “You’re holding it wrong”.

Cata says:

I have a question, being pretty new on Qt I don’t understand how events will be handled if I don’t subclass QThread.
Let’s say I have a worker class “Worker” and a worker thread and in my Worker class re-implements eventFilter method. When I try to do something like this:
Worker *workerObject = new Wroker();
QThread workerThread;
workerObject->moveToThread(&workerThread);
workerThread.installEventFilter(workerObject);
workerThread.start();

I get “QObject::installEventFilter(): Cannot filter events for objects in a different thread.”
After reading this post I assume that this should be the best way to go but even if I change thread affinity for my workerObject to workerThread by calling moveToThread method it doesn’t seem to work.
Instead if I subclass QThread and have my Worker class inherit QThread, reimplement “event” method and moveToThread(this) in the ctor it works like a charm and I can handle events.
Please shed some light on this.

Cata says:

It seems that I misunderstood the event handling in Qt, and the solution is obvious, I just needed to re-implement “event” method in my Worker class and don’t need an event filter at all. Sorry for rushing in with questions before being properly informed.

Sebastian Barth says:

I like this new way to use QThreads!
But there is a big problem with deleting worker classes:

On the old way I did this:
Code:
// In the subclass of QThread “WorkerThread”:
void run()
{
Worker worker;
worker.connect(…..);

exec();
}
Code:
// In the creating object that belongs to another thread (maybe the main thread):
void createThread()
{
this->workerThread = new WorkerThread(this);
}

Here the worker object are created inside the run() method and so on the new thread. When the created thread has finished, the run() method were left and on this way the worker object were deleted automatically since it was a local object ob the run() method.

But now, on the right way, I have to create both, the Qthreads AND the worker object, inside the creating context with new. Otherwise they will be deleted when I leave the scope of the creation context:

Code:
// In the creating object that belongs to another thread (maybe the main thread):
void createThread()
{
this->workerThread = new QThread();
this->worker = new Worker();
this->worker->connect(…);
this->worker->moveToThread(this->workerThread);
}

Now, when the instanciating object gets deleted, I have to take care that the QThread object and the worker object gets deleted as well but at the earliest when I have stopped the started thread.

I can use the parent child system (new QThread(this)) to take care that the QThread will be deleted when the creating object gets deleted. But I cannot use it for the worker class since it is on another thread!

It’s very hard to deal with this structure from outside if you want to use the “new style of using QThreads”. You have to care about all started worker objects, their QThreads and their started threads to be deleted at the correct time!
For this I have two suggestions that will solve this problems:

1. It should be allowed for QThreads to have chrildren that are moved to them.

2. The destructor of a QThread should send a quit() signal to “itself” and waits for its started thread to be finished. At the earliest when this thread has stopped, it starts to delete his childrens.

In other words: The QThread is the bridge between threads in Qt. To be consequent on the Qt structure / coding style with its parent-child paradigm, the QThread should be the owner (and deleter) of its children that are handled by its created thread.
If this is not going to be changed, the Qt parent-child structure is inconsequent.

What do you think about this?
Any ideas, problems, suggestions?

Sebastian Barth

NuShrike says:

So this is wrong then?

class SizeLoaderThread : public QThread
{
Q_OBJECT
public:
SizeLoaderThread()
{
moveToThread(this);
}
}

Guess where I found it … “photos” of http://qt.gitorious.org/qt-labs/scenegraph

So please, clean the Qt house before calling out everybody else.

Christophe Meessen says:

This works indeed very well and makes programming with threads much simpler.

My QThread object is now a member variable of the live object. In its constructor I now have

// Set this object to use thread event loop
moveToThread(&m_thread);

// Make sure object is notified when thread is started
connect( &m_thread, SIGNAL(started()), this, SLOT(started()));

// Start thread
m_thread.start();

The public slot methods are the actions that may be invoked asynchronously by the main thread. Signals will be sent back on completion. This makes interaction very simple.

There is apparently still a problem with this since I can’t prevent the main thread to call the slot method directly (without using a signal). The main thread will then execute the method synchronously which may not be the desired effect.

I suspect there could be a way to detect if the caller of the live object method is the m_thread instance or another thread. If it is another thread, it should then signal the method invocation and return so that the method is executed only by the m_thread object. Is there a way to invoke a private slot without a connection ?

Ton van den Heuvel says:

I would really like to see a response of the author to Sebastian Barth’s comment, as I’m struggling with the same problem right now.

Christophe Meessen says:

See my code example in the EDIT section of my question on StackOverflow.

It shows an example of a live object with graceful termination when the destructor is called and a doTask() method that can be called directly by any thread and that will delegate its execution to the live object’s thread.

http://stackoverflow.com/questions/3297456/invoke-slot-method-without-connection

This is a good example (if correct) on how to add background task support in Qt.

I used this in a Qt program controlling an X Ray scanner. The live object is for instance the detector driver object. Acquiring an image is a typical background task. Qt is a very impressive and powerful tool.

Jesse says:

I think NuShrike makes a good point. I’ve been using this example:

http://qt.gitorious.org/qt-labs/scenegraph/blobs/master/examples/photos/photos.cpp

…for a while. My thought was that this was the “official” way to make it happen.

Jon says:

If I want a thread with an event loop I *have* to subclass QThread, right? (since exec() is protected).

Or is there is another ‘preferred’ way for this as well?

Andre says:

Any chance that the documentation will actually be fixed? The docs for the current Qt 4.7 snapshot still look unchanged in this area.

Mathias says:

This is pretty old by now but I’ve just found it and I have to say: Thank you! Now QThread makes so much more sense to me. My suggestion: Don’t call it QThread if it isn’t a thread. Call it QThreadControl and I would’ve been fine from the start. (Would’ve been too if I had read the Qt-sources earlier).

Andrew says:

After scouring various links posted by Brad, I’ve come created an example. I think that everyone probably has this figured out already but just in case…
Credit: My example is based on Brad’s .tar.gz example found here.


class WriteFile : public QObject
{
Q_OBJECT

public:
WriteFile(QObject *parentIN = 0) : parent(parentIN)
{
ConnectSignalSlots();
}

void DoAll()
{
this->moveToThread(&threadObj);
threadObj.start();
}

void ConnectSignalSlots()
{
QObject::connect(&threadObj, SIGNAL(started()), this, SLOT(CallFileWrite()));
QObject::connect(this, SIGNAL(fileWrite(QString,QString)), this, SLOT(writingFile(QString,QString)));
QObject::connect(this, SIGNAL(FinishWritingThread()), &threadObj, SLOT(quit()));
QObject::connect(&threadObj, SIGNAL(finished()), this, SLOT(ThreadFinishedCheck()));
}

QThread threadObj;
QObject *parent;

public slots:
void writingFile(const QString &textOUT, const QString &altTextOUT)
{
//do all the file writing
printf("Yup.. this is writing stuff: %d, and %s.\n", textOUT.toStdString(), altTextOUT.toStdString());
emit FinishWritingThread();
}
void CallFileWrite()
{
emit fileWrite("apples and bananas", "Karmin is hot");
}
void ThreadFinishedCheck()
{
printf("The thread has successfully been terminated.\n");
}

signals:
void fileWrite(const QString &textIN, const QString &altTextIN);
void FinishWritingThread();
};

int main()
{
WriteFile testThreadClass;
testThreadClass.DoAll();
}

Andrew says:

Apologies for the incorrect “printf” usage.

Ricardo says:

useless!
:(
T_T
x_X

I’ve tried using moveToThread(), not using it, subclassing and not subclassing… that slot wont get executed… God I miss java :(

JKSH says:

Post your issue at the forums (http://qt-project.org/forums/); someone should be able to help you

As a starting point, you need to do things in this order:
1. Create the QThread
2. Move the QObject to the QThread
3. Connect the QObject’s slot to a signal
4. Start the QThread
5. Emit the signal that’s connected to the slot

Markus Goetz says:

FYI, Olivier posted a reply to this blog post :-)
“You were not doing so wrong”

http://woboq.com/blog/qthread-you-were-not-doing-so-wrong.html

Melvin says:

Having read this I thought it was extremely informative. I
appreciate you taking the time and effort to put this article together.
I once again find myself spending way too much time both reading and leaving comments.
But so what, it was still worth it!

7 says:

Last week I was doing some multithreading, following the “community guidelines” and noticed that threads and workers weren’t getting destroyed at all, and was just about to ask around the forum, but this article pretty much answers my questions.

Commenting closed.