Unsolved Simplest app with QThread crashes on exit
-
#include <QCoreApplication> #include <QThread> #include <QDebug> class First : public QObject { Q_OBJECT public slots: void callSlot() { qDebug() << "First slot called from thread ";} }; class Second : public QObject { Q_OBJECT First first; QThread thread; signals: void callSignal(); public: Second() { first.moveToThread(&thread); connect(this, &Second::callSignal, &first, &First::callSlot); thread.start(); } ~Second() { thread.quit(); thread.wait(); } }; int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); Second second; emit second.callSignal(); return a.exec(); } #include "main.moc"
Why should this app crash? Implementation doesn't even differ from what docs show here
-
@Amir-Afendin said in Simplest app with QThread crashes on exit:
Why should this app crash?
Run your app in Debug mode.
What does your crash stack trace say?
-
@Amir-Afendin said in Simplest app with QThread crashes on exit:
Implementation doesn't even differ from what docs show here
It does slightly. The worker object in the docs is allocated in the heap. By looking at the code it crashes in the destructor of the worker object (in
QObject::~QObject
) where there is some logic that references the current object thread. Since the thread has already been destroyed by the stack unwinding you'd get a dangling pointer.In conclusion, what @JKSH said:
What does your stack trace say?PS.
I expect that exchanging the two member declarations would fix it. That is:// ... QThread thread; First first;
-
-
@kshegunov
Screenshots above were made with app version where I allocate worker int the heap. -
This doesn't look like an active trace. Take the backtrace after the crash signals the debugger and stops the application from running.
-
Your testcase works fine for me (only had to add a line to exit the app - QTimer::singleShot(2000, qApp, QCoreApplication::quit); )
-
Looks like if you create empty "Qt Console Application" it crashes anyway. So there's no thread problem here I guess.