What happens to the thread affinity of a QObject created within a worker thread which then terminates?

后端 未结 6 764
庸人自扰
庸人自扰 2021-02-05 04:39

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

6条回答
  •  太阳男子
    2021-02-05 05:23

    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!

提交回复
热议问题