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

Murphy, Sean smurphy at walbro.com
Thu Feb 25 18:24:06 CET 2016


> >    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.

Just when I think I have QObjects and QThreads figured out, I realize I don't... How do I correctly handle my situation?

I've got a QObject-based class that talks to a custom device and needs to block while making reads/writes to that device. This thread runs the entire duration of my application, because the work it's doing never finishes, it just monitors the device for messages and notifies my UI class when data comes in.

So currently I'm doing this:

myGUIObject.h:
private:
  myBlockingObject* blocking;
  QThread* thread;

myGUIObject.cpp:
myGUIObject()
{
  thread = new QThread(this);
  blocking = new myBlockingObject();
  blocking->moveToThread(thread);
}

How/where do I properly delete "blocking"? Right now I'm doing this:
~myGUIObject()
{
    thread->exit();
    blocking->deleteLater();
}

But Thiago's comment "A QObject can only be destroyed in its thread of affinity" sounds like it's not the right way to do it?
Sean


More information about the Interest mailing list