【发布时间】:2021-02-13 15:11:51
【问题描述】:
QFutureWatcher 类在它正在监视的 QFuture 完成时发出信号 finished()。
如何观看多个QFuture?
我正在使用QtConcurrent::run() 并行运行两个线程,并希望在两个线程都完成后得到一个信号。
【问题讨论】:
-
其中一个答案对您有用吗?
标签: c++ multithreading qt
QFutureWatcher 类在它正在监视的 QFuture 完成时发出信号 finished()。
如何观看多个QFuture?
我正在使用QtConcurrent::run() 并行运行两个线程,并希望在两个线程都完成后得到一个信号。
【问题讨论】:
标签: c++ multithreading qt
我会这样处理问题:
根据需要创建尽可能多的QFutureWatchers
将所有QFutureWatchers 添加到列表中,分别。矢量,例如m_futureWatchers:
m_futureWatchers.append(futureWatcher);
将QFutureWatcher::finished 信号连接到同一个插槽,例如handleFinished:
connect(futureWatcher, &QFutureWatcher<int>::finished, this, MyClass::handleFinished);
在handleFinished 插槽中检查QFutureWatcher::isFinished 并做出相应反应:
bool allAreFinished = true;
for (auto *futureWatcher : m_futureWatchers)
allAreFinished &= futureWatcher->isFinished();
if (allAreFinished) {
// doSomething
}
注意:对于只有两个未来观察者,拥有两个成员变量可能更容易,例如m_futureWatcher1 和 m_futureWatcher1,而不是列表,并在 handleFinished 插槽中检查它们,如下所示:
if (m_futureWatcher1->isFinished() && m_futureWatcher2->isFinished) {
...
}
【讨论】:
您可以为 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);
【讨论】: