Search code examples
c++multithreadingqt

Qt C++ moveToThread()


I've just started working with Qt on Windows and read about moveToThread() function. Would it be ok if I write like this:

class Worker : public QObject
{
    Q_OBJECT
private:
    QThread* thread;
public:
    void GoToThread() {
        thread = new QThread();
        this->moveToThread(thread);
    }
    void DoWork() {
        //long work
    }
};

Worker* w = new Worker();
w->GoToThread();
w->DoWork();

And what exactly would this code do? Would it put itself to the thread? Would I be able to call DoWork() outside?


Solution

  • In the example you gave, DoWork() would execute on the caller's thread.

    If you want DoWork() to be done on the Worker object's thread, you should have DoWork() be a slot that can be invoked either by emitting a signal that it has been connected to or by calling QMetaObject::invokeMethod() to 'call' it.

    Basically, moving a Q_OBJECT to another thread makes that Q_OBJECT use an event queue associated with that thread, so any events delivered to that object via the event queue will be handled on that thread.