What does it mean by "thread owns a QObject"?
-
What does it mean by "thread owns a
QObject
"? I found this in the docCalling delete on a
QObject
from a thread other than the one that owns the object (or accessing the object in other ways) is unsafe [...]
By default, the thread that owns aQObject
is the thread that creates theQObject
, but not afterQObject::moveToThread()
has been called. -
Hi and welcome to devnet,
Exactly what it said in the documentation you quoted: the thread in which you create the object owns it. You have always at least one thread in your application. You can create more if needed and thus you have to take good care on where and when the objects are created to ensure they are owned by the expected thread or are moved to it.
-
@haccks said in What does it mean by "thread owns a QObject"?:
QObject::moveToThread() changes thread affinity and also the ownership of the object. Are they same?
In this case, yes. As @SGaist said above, the thread where the
QObject
was created in, owns this object. If you move it to thread X, the ownership is also moved. The movedQObject
"lives" in thread X now.You can check the affinity of every
QObject
by callingLike
QThread* myThread = new QThread(); QObject* obj = new QObject(); // obj in main thread where it was created if(obj->thread() == this->thread()) qDebug() << "Obj in Main thread"; obj->moveToThread(myThread); // after moving, ownership went to "myThread" if(obj->thread() == myThread()) qDebug() << "Obj in myThread"; // ... // "Worker" approach: // connect signals for thread control // and start myThread afterwards
-
@haccks said in What does it mean by "thread owns a QObject"?:
a QObject living in thread means this thread will handle its queued signals/events
Yes, or in other words, the slot/function will run in the thread where the receiver
QObject
lives in.
Therefore you should also always useQt::QueuedConnection
in a connect statement, when dealing with more than one thread (or let Qt decide, which works best in most cases). If you force aQt::DirectConnection
across threads, the function will run in the calling thread and cause unwanted behavior or nothing happens at all. -
@haccks said in What does it mean by "thread owns a QObject"?:
it can still be used/accessed in the thread where it is declared?
Define "used"...
In general, as long as the pointer is valid, it works but you should not call functions directly. Use signals to communicate instead.