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

Lorenz Haas lykurg at gmail.com
Wed Feb 24 10:22:18 CET 2016


Hi André,

> That should work just fine, with the exception of using &m_thread as a
> member.

thanks for your answer. I am, however, not sure what you mean
regarding the m_thread member. For a better understanding here is a
working example I have in mind:

**************************************************
#include <QtCore>

class Foo : public QObject
{
   Q_OBJECT
public:
   Foo() : QObject(nullptr) {
      moveToThread(&m_thread);
      m_thread.start();
   }

   ~Foo() {
      m_thread.quit();
      m_thread.wait();
   }

   void printFooInformation() const {
      qDebug() << "foo affinity" << thread();
   }

   void printThreadInformation() const {
      qDebug() << "m_thread affinity" << m_thread.thread();
   }

private:
   QThread m_thread;
};

int main(int argc, char *argv[])
{
   QCoreApplication a(argc, argv);
   qDebug() << "GUI affinity" << a.thread();
   Foo *foo = new Foo;
   foo->printThreadInformation();
   foo->printFooInformation();
   return a.exec();
}

#include "main.moc"
**************************************************

Of course, every instance of Foo would create a new thread and
therefor multiple instance of Foo would _not_ share the same thread.
Did you mean that? (In my special case this is intended.)

Lorenz



More information about the Interest mailing list