I’ve seen this pattern quite some times now:
QFutureWatcher<void> watcher;
watcher.setFuture(QtConcurrent::run([]{ … }));
QEventLoop loop;
QObject::connect(&watcher, &decltype(watcher)::finished, &loop, &QEventLoop::quit);
loop.exec();
I wonder though if this is safe, because if qApp->quit();
quits this eventloop the code after it probably does not take into account that the thread may not be finished yet. So does QCoreApplication::quit quit local eventloops? And even if not is this pattern safe to serialize background tasks?
1
Yes, it does.
#include <QCoreApplication>
#include <QFutureWatcher>
#include <QtConcurrent>
void localExec()
{
auto *w = new QFutureWatcher<void>;
w->setFuture(QtConcurrent::run([]{ QThread::sleep(10); }));
QEventLoop loop;
QObject::connect(w, &QFutureWatcher<void>::finished, &loop, &QEventLoop::quit);
loop.exec();
qDebug() << "is finished:" << w->isFinished();
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QTimer::singleShot(0, [&]{ localExec(); });
QTimer::singleShot(5000, []{ QCoreApplication::quit(); });
return a.exec();
}
is finished: false
Qt 6.5.3
0