Let\'s say I call QtConcurrent::run()
which runs a function in a worker thread, and in that function I dynamically allocate several QObjects (for later use). Since
Although this is an old question, I recently asked the same question, and just answered it using QT 4.8 and some testing.
AFAIK you cannot create objects with a parent from a QtConcurrent::run function. I have tried the following two ways. Let me define a code block then we will explore the behavior by selecting POINTER_TO_THREAD.
Some psuedo code will show you my test
Class MyClass : public QObject
{
Q_OBJECT
public:
doWork(void)
{
QObject* myObj = new QObject(POINTER_TO_THREAD);
....
}
}
void someEventHandler()
{
MyClass* anInstance = new MyClass(this);
QtConcurrent::run(&anInstance, &MyClass::doWork)
}
Ignoring potential scoping issues...
If POINTER_TO_THREAD
is set to this
, then you will get an error because this
will resolve to a pointer to the anInstance
object which lives in the main thread, not the thread QtConcurrent has dispatched for it. You will see something like...
Cannot create children for a parent in another thread. Parent: anInstance, parents thread: QThread(xyz), currentThread(abc)
If POINTER_TO_THREAD
is set to QObject::thread()
, then you will get an error because because it will resolve to the QThread object in which anInstance
lives, and not the thread QtConcurrent has dispatched for it. You will see something like...
Cannot create children for a parent in another thread. Parent: QThread(xyz), parents thread: QThread(xyz), currentThread(abc)
Hope my testing is of use to someone else. If anyone knows a way to get a pointer to the QThread which QtConcurrent runs the method in, I would be interested to hear it!