Search code examples
multithreadingqtsignals-slots

Qt thread does not stop after calling exit/quit


I'm trying to find a better understanding of Qt signals and slots in conjunction with threads. So I tried this minimal application:

foo.h:

#include <QObject>

class A : public QObject {
  Q_OBJECT

public:
  void doit();

signals:
  void x();
};

class B : public QObject {
  Q_OBJECT

public slots:
  void h();
};

foo.cpp:

#include "foo.h"

#include <QThread>
#include <QCoreApplication>

void B::h() {
  qDebug("[%d] B::h() here!", (int) QThread::currentThreadId());
  QCoreApplication::instance()->quit();
}

void A::doit() {
  qDebug("[%d] emitting...", (int) QThread::currentThreadId());
  emit x();
}

int main(int argc, char* argv[]) {
  QCoreApplication app(argc, argv);
  A a;
  B b;
  QObject::connect(&a, SIGNAL(x()), &b, SLOT(h()));
  QThread t;
  t.start();
  b.moveToThread(&t);
  a.doit();
  t.wait();
  return 0;
}

Everything is fine, only the t.wait() at the end never returns. My understanding is calling quit() should stop the event loop, which means exec() should return and so should run() and thread execution should stop. Am I missing something?


Solution

  • QCoreApplication::quit () is not stated as thread-safe method so you can't call it from another thread. Your application can crash or get an undefined behavior(UB).

    t.wait() will never return because the running thread is constantly waiting for events. To stop the thread you must call QThread::quit () [slot]

    If you want to quit the application after the work is done you have to emit a signal, which is connected to QCoreApplication::quit () [static slot]

    If you want to stop the worker thread after the work is done you also have to emit a signal, connected to void QThread::quit () [slot]

    Added: Threads, Events and QObjects for further reading

    Important notice: You must call QCoreApplication::exec() in order to be able to use signal & slot mechanism between threads, queued connections.

    From Qt QThread doc:

    Each QThread can have its own event loop. You can start the event loop by calling exec(); you can stop it by calling exit() or quit(). Having an event loop in a thread makes it possible to connect signals from other threads to slots in this thread, using a mechanism called queued connections. It also makes it possible to use classes that require the event loop, such as QTimer and QTcpSocket, in the thread. Note, however, that it is not possible to use any widget classes in the thread.

    Doc for Qt::QueuedConnection:

    The slot is invoked when control returns to the event loop of the receiver's thread. The slot is executed in the receiver's thread.