将QFutures列表设置为QFutureWatcher

时间:2015-06-29 05:46:21

标签: qt qtconcurrent qfuture

是否可以向QFuture添加多个QFutureWatcher? 我想向QFutureWatcher添加多个功能,并在所有线程完成后收到通知。

QFutureSynchronizer没有帮助我,因为它没有完成信号

1 个答案:

答案 0 :(得分:0)

我以这种方式使用它: 哪里

QFutureSynchronizer<...> _synchronizer;
QFutureWatcher<...> _watcher;

-

void Service::request(const QString& word)
{
    QMutexLocker lock{&_mutex};

    auto future = QtConcurrent::run([this, word]()
                                    {
                                        //...
                                    });
    _synchronizer.addFuture(future);
    if (_watcher.isRunning() == false)
    {
        _watcher.setFuture(future);
    }
}

void Service::onReady()
{
    QMutexLocker lock{&_mutex};
    auto futures = _synchronizer.futures();
    _synchronizer.clearFutures();
    auto removeFrom = std::remove_if(futures.begin()
                                     , futures.end()
                                     , [](const QFuture<QPair<QString, QVector<QString>>>& element)
            {
                return element.isFinished();
            });

    for (auto it = futures.begin(); it != removeFrom; ++it)
    {
        _synchronizer.addFuture(*it);
    }
    for (auto it = removeFrom; it != futures.end(); ++it)
    {
        //...
    }

    auto waitingOnes = _synchronizer.futures();
    if (waitingOnes.isEmpty() == false && _watcher.isFinished())
    {
        _watcher.setFuture(waitingOnes.front());
    }
}