A question about QEventLoop.
-
Hello everyone,
#include <QApplication> #include <QEventLoop> #include <QTimer> #include <QMetaObject> #include <QThread> int main(int argc, char* argv[]) { QApplication app(argc, argv); auto obj = new QObject(); auto th = new QThread(); th->start(); obj->moveToThread(th); for (size_t i = 0; i < 5; i++) { QThread::msleep(500); QMetaObject::invokeMethod(obj, [=]() { printf("%d start ", i); QEventLoop loop; QTimer::singleShot(5000, &loop, &QEventLoop::quit); loop.exec(); //QThread::sleep(10); printf("%d end ",i ); }); } return app.exec(); }
The printed result of this code is "0 start 1 start 2 start 3 start 4 start 4 end 3 end 2 end 1 end 0 end",
But as expected, the eventloop of 0 should be the first to end, so the 0 end should be printed first. -
@John-Van said in A question about QEventLoop.:
But as expected, the eventloop of 0 should be the first to end, so the 0 end should be printed first.
That is simply not possible. Only the inner most event loop is processing events, and it does so for the entire thread. So only event loop 4 is active, the rest are blocked.
Event loop 0 is indeed the first one to have its
quit
slot called, but that only signals for it to end at the first available opportunity- which isn't right now, as it is blocked on executing loop 1, which is blocked on executing loop 2, etc. It can exit only once all of that unwinds, so last.