2

我在我的应用程序中构建了一个基于 QFuture 的异步网络外观。大致是这样工作的:

namespace NetworkFacade {
    QByteArray syncGet(const QUrl& url) {
        QEventLoop l;
        QByteArray rc;

        get(url, [&](const QByteArray& ba) {
            rc = ba;
            l.quit();
        });

        l.exec();
        return rc;
    }

    void get(const QUrl& url, const std::function<void (const QByteArray&)>& handler) {
        QPointer<QNetworkAccessManager> m = new QNetworkAccessManager;

        QObject::connect(m, &QNetworkAccessManager::finished, [=, &m](QNetworkReply *r) {
            QByteArray ba;

            if (r && r -> error() == QNetworkReply::NoError)
                ba = r -> readAll();

            m.clear();

            if (handler)
                handler(ba);
        });
        m -> get(QNetworkRequest(url));
    }
}

我有一个QTimer触发主线程的调用,它执行以下操作(显然简化了):

foreach(Request r, requests) {
    futures.push_back(get(r));
}

foreach(QFuture<SomeType> f, futures) {
    f.waitForFinished();
    [do stuff with f.result()]
}

我的假设是waitForFinished()在后台线程执行我的网络请求时会阻塞主线程。相反,我得到一个qFatal错误:

ASSERT: "m_blockedRunLoopTimer == m_runLoopTimer" in file eventdispatchers/qeventdispatcher_cf.mm, line 237

在堆栈跟踪中,我waitForFinished()在主线程上看到了我的,但是我看到的不是被阻塞(从下往上读取):

com.myapp   0x0008b669 QEventDispatcherCoreFoundation::processEvents(QFlags<QEventLoop::ProcessEventsFlag>) + 1753
com.myapp   0x000643d7 QIOSEventDispatcher::processEvents(QFlags<QEventLoop::ProcessEventsFlag>) + 823
com.myapp   0x0130e3c7 QEventLoop::processEvents(QFlags<QEventLoop::ProcessEventsFlag>) + 119
com.myapp   0x0130e5fb QEventLoop::exec(QFlags<QEventLoop::ProcessEventsFlag>) + 539
com.myapp   0x0003a550 NetworkFacade::syncGet(QUrl const&) + 208
com.myapp   0x00037ed1 QtConcurrent::StoredFunctorCall0<std::__1::shared_ptr<QuoteFacade::Quote>, QuoteFacade::closingQuote(QString const&, QDate const&)::$_0>::runFunctor() + 49
com.myapp   0x00038967 QtConcurrent::RunFunctionTask<std::__1::shared_ptr<QuoteFacade::Quote> >::run() + 87
com.myapp   0x00038abc non-virtual thunk to QtConcurrent::RunFunctionTask<std::__1::shared_ptr<QuoteFacade::Quote> >::run() + 28
com.myapp   0x010dc40f QThreadPoolPrivate::stealRunnable(QRunnable*) + 431
com.myapp   0x010d0c35 QFutureInterfaceBase::waitForFinished() + 165

因此,与其等待QFuture获得值,不如在主线程上发出我所谓的并发任务。这会导致get()我上面概述的函数被调用,它侦听QEventLoop. 与此同时,QTimer火灾再次发生,我从上面得到了断言。

我做错了什么,还是完全有效的QtConcurrent::run可以导致控制回到主线程?

=== 更新 1

@peppe:正在执行的 lambda 只是执行一个 HTTP GET 并生成将 JSON 响应解析为一个SomeType对象。结果通过QFuture.

=== 更新 2

显然这是设计使然。从qfutureinterface.cppQt 5.4.0 第 293-295 行开始:

// To avoid deadlocks and reduce the number of threads used, try to
// run the runnable in the current thread.
d->pool()->d_func()->stealRunnable(d->runnable);
4

1 回答 1

5

显然这是设计使然。来自 Qt 5.4.0 第 293-295 行的 qfutureinterface.cpp:

// To avoid deadlocks and reduce the number of threads used, try to
// run the runnable in the current thread.
d->pool()->d_func()->stealRunnable(d->runnable);

QtConcurrent::run()返回QFuture使用 a 实现的 a QFutureInterface。在和QFutureInterface中都包含该代码。waitForFinished()waitForResult()

stealRunnable是一个未记录的私有方法QThreadPool。它在 headerdoc 中如此描述:

/*!
    \internal
    Searches for \a runnable in the queue, removes it from the queue and
    runs it if found. This function does not return until the runnable
    has completed.
*/

所以我们最终得到的是,如果QRunnable内部创建的 byQtConcurrent::run()尚未从QThreadPool分配给它的任何内容中出列,则调用waitForFinishedorwaitForResult将导致它在当前线程上运行(即不并发。)

这意味着像这样的代码(以及我在问题中所做的)可能会以神秘的方式失败:

foreach (FuncPossiblyTriggeringQEvents fn, tasks) {
    futures.push_back(QtConcurrent::run(fn));
}

foreach (QFuture<> f, futures) {
    f.waitForFinished(); // Some of my tasks will run in this thread, not concurrently.
}

QNetowrkAccessManager通过使用std::futurestd::async.

于 2015-02-05T03:00:19.103 回答