PDA

View Full Version : changing thread affinity properly



mentalmushroom
3rd March 2011, 15:33
Hi there. I'd like to know what is the proper way of using moveToThread function. I have QTcpSocket object as a member of QThread derived class. I've got some warning messages about thread affinity. To solve that I call moveToThread inside my thread class:




class MyDownloadingThread: public QThread
{
//...
protected:
QTcpSocket socket;
//...
}

//....

MyDownloadingThread::MyDownloadingThread(ParentThr ead *parentThread)
{
this->parentThread = parentThread;
this->socket.moveToThread(this);
}


Is it correct? Or maybe I should call moveToThread after starting the target thread?

high_flyer
3rd March 2011, 15:54
if you check in a debugger (or debug output) you will see that your case 'this' and 'parentThread' are the same.
Your QThread starts a new thread only after start() has been called (which internally means after run() hast been called).

MarekR22
3rd March 2011, 17:17
Read this article. There is good explanation (http://labs.qt.nokia.com/2010/06/17/youre-doing-it-wrong/).
In general it means that this information is needed for connection (automatic or queued) in which tread slot should be run when connected signal is emitted.
Note that:

you don't need to subclass QThread
never move thread to itself.

mentalmushroom
3rd March 2011, 19:05
thanks for the article. now i see it is not necessary to subclass QThread, but, honestly, i don't see much difference. We can write something like


QThread *thread = new QThread;
Worker *worker = new Worker;
worker->moveToThread(thread);

// now start the thread
thread->start();


or we can subclass it and move the object in the constructor:


MyThread::MyThread()
{
myobject.moveToThread(this);
}


in both cases object is moved to the thread before it is started, so in both cases the object seems to be moved to the thread interface that QThread is.

and i don't move thread to itself - i move objects to a thread (see my thread declaration).