changing thread affinity properly
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:
Code:
class MyDownloadingThread
: public QThread{
//...
protected:
//...
}
//....
MyDownloadingThread::MyDownloadingThread(ParentThread *parentThread)
{
this->parentThread = parentThread;
this->socket.moveToThread(this);
}
Is it correct? Or maybe I should call moveToThread after starting the target thread?
Re: changing thread affinity properly
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).
Re: changing thread affinity properly
Read this article. There is good explanation.
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.
Re: changing thread affinity properly
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
Code:
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:
Code:
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).