jeudi 4 août 2016

QThread & C++11 lambda: wait for finished

I wish to execute code from a lambda asynchronously while keeping an eventloop running and I figured: this could work...

auto thread = QSharedPointer<QThread>(new QThread);

QEventLoop l;
connect( thread.data(), &QThread::finished, &l, &QEventLoop::quit );
connect( thread.data(), &QThread::started, [=]() {
    for(int i=0; i<100; ++i ) {
        qDebug() << "waiting... " << i;
    }
    QThread::currentThread()->sleep(10);
} );
thread->start();
l.exec();
auto const fin = thread->wait();
qWarning() << fin;

Everything is working as expected but: I doesn't get the part when the thread finishes its lambda function. It seems finished is not emitted and wait (even without the extra eventloop) will block forever.

How do I get the event loop to exit or the wait to return? Or this there a better way to let a lambda run in another thread and wait for it with an non-blocked event loop?

Thank you

Aucun commentaire:

Enregistrer un commentaire