Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Qt moveToThread: What resources are brought with the object?

Say I have created a QObject a and it has a member QObject b. (Actually, both A and B are subclasses of QObject, and class A has a member B b.)

When b is created, its parent is 0 (default). In the code, if I never set b's parent to a, and if I call movetothread() to move a into a worker thread, will b be moved into that thread too?

If it is not moved, if I call b.init() from the worker thread (the one I moved a into) which use new operator to create another QObject that has b as a parent, then I will get the following error, right?

QObject: Cannot create children for a parent that is in a different thread

like image 465
Nyaruko Avatar asked Oct 19 '14 16:10

Nyaruko


2 Answers

As the Qt documentation for QObject::moveToThread states: -

Changes the thread affinity for this object and its children. The object cannot be moved if it has a parent. Event processing will continue in the targetThread.

In this case, a parent is an object whose child is set either by passing the parent in the constructor or by calling setParent on the child. It is not an an object which has a pointer to another object.

In the code, if I never set b's parent to a, and if I call movetothread() to move a into a worker thread, will b be moved into that thread too?

So, no, if b's parent is not set and you call moveToThread on 'a', 'b' will still have the original thread affinity.

If it is not moved, if I call b.init() from the worker thread...

If you've moved 'a' and not 'b' to a worker thread, then you should not be calling b.init directly from the worker thread. Instead, the object in the worker thread ('a') should emit a signal for an object in the original thread to call b.init from a connected slot

like image 198
TheDarkKnight Avatar answered Nov 04 '22 05:11

TheDarkKnight


will b be moved into that thread too?

No, QObject doesn't know that b is a member of a. (You didn't say whether a holds a pointer to b or whether it holds b directly, but the answer is the same in both cases.)

then I will get the following error, right?

The child of a QObject must always be created in the thread which owns the parent. I'm reluctant to say that you will definitely get an error, because the behaviour may be undefined.

See Threads and QObject.

like image 29
Oktalist Avatar answered Nov 04 '22 05:11

Oktalist