[Interest] moveToThread used in constructor to move "this"

André Somers andre at familiesomers.nl
Thu Feb 25 07:55:54 CET 2016



Op 24/02/2016 om 18:23 schreef Thiago Macieira:
> On quarta-feira, 24 de fevereiro de 2016 10:22:18 PST Lorenz Haas wrote:
>>     Foo() : QObject(nullptr) {
>>        moveToThread(&m_thread);
>>        m_thread.start();
>>     }
>>
>>     ~Foo() {
>>        m_thread.quit();
>>        m_thread.wait();
>>     }
> This destructor is either never run or deadlocks.
>
> A QObject can only be destroyed in its thread of affinity. So the above is
> running in that m_thread thread, which means it hasn't exited. Waiting for it
> to exit will wait forever.
>
Thanks indeed; I did not spot this issue either.

Would it be possible to circumvent this issue by moving the thread 
object onto its own thread too?

    Foo() : QObject(nullptr) {
       moveToThread(&m_thread);
       m_thread->moveToThread(m_thread);
       m_thread.start();
    }


Looks like the much debated move-QThread-onto-its-own-thread 
antipattern, but it's not the same obviously.

André




More information about the Interest mailing list