PDA

View Full Version : MoveToThread clarification



Thuan Seah Tan
3rd February 2012, 07:08
I read some article on the Qt dev blog which suggest the proper way to do multithread stuff is to use moveToThread instead of subclassing QThread.

I have this class that does some serious work which i like to run on a separate thread.

So basically the code look something like this:



.H file
class Data : QObject
{
public:
void update();
};

class Worker : QObject
{
public:
void setData( Data* data ) { mData = data; }

signals:
void workCompleted();

public slots:
void doWork();

private:
Data* mData;
};
class Master : QObject
{
Master() { mWorker = new Worker; mWorkerThread = new QThread; }
void askWorkerToWork();

private:
Worker* mWorker;
QThread* mWorkerThread;
};

.CPP file
void Data::update()
{
UpdateEvent e("Updated");
QCoreApplication::sendEvent(this, &e);
}

void Worker::doWork()
{
// run some computation
this->moveToThread(QCoreApplication::instance()->thread());
mData->update();
emit workCompleted();
}

void Master::askWorkerToWork()
{
Data* data = new Data;
mWorker->setData(data);
mWorker->moveToThread(mWorkerThread);
connect(mWorkerThread, SIGNAL(started()), mWorker, SLOT(doWork()), Qt::UniqueConnection);
connect(mWorker, SIGNAL(workCompleted()), mWorkerThread, SLOT(quit()), Qt::UniqueConnection);
mWorkerThread->start();
}



I would like to know given the above setup does Qt automatically move the mWorker back to thread which Master object is created when the thread quits? Or do I have to do a moveToThread as shown in the code manually?

Does the moveToThread function actually move the object to the target thread immediately? Qt complains that I cannot call the function QCoreApplication::sendEvent in the Data object because it is created on a different thread.

wysota
3rd February 2012, 10:32
Qt doesn't move any objects anywhere on its own. Using sendEvent() on an object that lives in a different thread doesn't make any sense. Use postEvent() instead.