【问题标题】:How can I watch more than one QFuture?如何观看多个 QFuture?
【发布时间】:2021-02-13 15:11:51
【问题描述】:

QFutureWatcher 类在它正在监视的 QFuture 完成时发出信号 finished()。 如何观看多个QFuture? 我正在使用QtConcurrent::run() 并行运行两个线程,并希望在两个线程都完成后得到一个信号。

【问题讨论】:

  • 其中一个答案对您有用吗?

标签: c++ multithreading qt


【解决方案1】:

我会这样处理问题:

  1. 根据需要创建尽可能多的QFutureWatchers

  2. 将所有QFutureWatchers 添加到列表中,分别。矢量,例如m_futureWatchers:

     m_futureWatchers.append(futureWatcher);
    
  3. QFutureWatcher::finished 信号连接到同一个插槽,例如handleFinished:

     connect(futureWatcher, &QFutureWatcher<int>::finished, this, MyClass::handleFinished);
    
  4. handleFinished 插槽中检查QFutureWatcher::isFinished 并做出相应反应:

     bool allAreFinished = true;
    
     for (auto *futureWatcher : m_futureWatchers)
         allAreFinished &= futureWatcher->isFinished();
    
     if (allAreFinished) {
         // doSomething
     }
    

注意:对于只有两个未来观察者,拥有两个成员变量可能更容易,例如m_futureWatcher1m_futureWatcher1,而不是列表,并在 handleFinished 插槽中检查它们,如下所示:

if (m_futureWatcher1->isFinished() && m_futureWatcher2->isFinished) {
    ...
}

【讨论】:

    【解决方案2】:

    您可以为 Qt 使用第 3 方 AsyncFuture 库:

    将多个不同类型的future组合成一个future对象:

    /* Combine multiple futures with different type into a single future */
    
    QFuture<QImage> f1 = QtConcurrent::run(readImage, QString("image.jpg"));
    
    QFuture<void> f2 = observe(timer, &QTimer::timeout).future();
    
    QFuture<QImage> result = (combine() << f1 << f2).subscribe([=](){
        // Read an image but do not return before timeout
        return f1.result();
    }).future();
    
    QCOMPARE(result.progressMaximum(), 2);
    

    【讨论】:

      猜你喜欢
      • 2018-12-15
      • 2017-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-21
      • 2012-05-30
      相关资源
      最近更新 更多