PDA

View Full Version : QObject::setParent across threads.



psih128
14th May 2010, 21:05
Hi

I'm having some problems with the QObject::setParent() function across threads. I'm seeing this behavior on windows only. On mac it works fine. Qt 4.6.2 in used on both platforms.
Here is the code:


MyObject *object = new MyObject();
if (parent) {
if (parent->thread() != object->thread()) {
object->moveToThread(parent->thread());
}
Q_ASSERT(parent->thread() == object->thread());
object->setParent(parent);
}


The error message is as follows:

Cannot send events to objects owned by a different thread. Current thread 588d088. Receiver 'MyObject' (of type 'MyObject') was created in thread a4f690

What could be wrong?

wysota
15th May 2010, 02:31
QObject is not thread-safe, accessing its members from thread other than that which the object belongs to may lead to a crash. Furthermore objects can't have a parent that lives in a diffrent thread than they do.

psih128
15th May 2010, 03:51
that's why I call movetoThead before calling setParent.

the docks mention that QObjects are not thread safe, but it does not mean that they can not be used across threads at all... Also the docs specifically warn the user when the given function is not thread safe.
Which part exactly causes problems?
1) object construction should work fine
2) moveToThread should be thread safe - the object is pushed away from the thread, in which it has been created.
3) setParent ??

From the error message I'm guessing that moveToThread have not finished something?

wysota
15th May 2010, 09:01
that's why I call movetoThead before calling setParent.
You cannot "pull" an object from another thread to your own thread. Only the thread that owns the object can call moveToThread().


the docks mention that QObjects are not thread safe, but it does not mean that they can not be used across threads at all...
That's exactly what "not thread-safe" means - the same object can't be called concurrently from different threads.


2) moveToThread should be thread safe - the object is pushed away from the thread, in which it has been created.
See above


3) setParent ??
It's definitely not thread-safe :)

ahmedb
21st January 2014, 16:01
the statement " setParent(parent)" isn't working because "moveToThread" has finished its work perfectly :)

- moveToThread() moved the object to another thread other than the current, so that you can not call setParent() of the object anymore.

and the problem is that you can not setParent() to a parent that is not the current thread also ( before calling moveToThread) !

have you solved this problem ?