Qt documentation says the following about QtConcurrent::blockingMap:
Note: This function will block until all items in the sequence have been processed.
Documentation for QtConcurrent::map is otherwise identical. Also it returns QFuture<void>
instead of void
.
Documentation for QFuture has the following remark:
The waitForFinished() function causes the calling thread to block and wait for the computation to finish, ensuring that all results are available.
Thus, I expected that QtConcurrent::blockingMap(seq, f)
is identical to QtConcurrent::map(seq, f).waitForFinished()
. However, it isn't.
#include <QObject>
#include <QtConcurrent>
class Foo : public QObject {
Q_OBJECT
public:
explicit Foo(QObject *parent = nullptr) : QObject(parent) {
connect(this, &Foo::signal, this, &Foo::slot, Qt::AutoConnection);
}
void startMapWithWaiting() {
qDebug("startMapWithWaiting");
slot_counter = 0;
std::atomic_int signal_counter = 0;
QtConcurrent::map(nums, [&](auto &&num) {
++signal_counter;
emit signal();
}).waitForFinished();
qDebug("result: %d signals, %d slots", int(signal_counter), int(slot_counter));
slot_counter = 0;
}
void startBlockingMap() {
qDebug("startBlockingMap");
slot_counter = 0;
std::atomic_int signal_counter = 0;
QtConcurrent::blockingMap(nums, [&](auto &&num) {
++signal_counter;
emit signal();
});
qDebug("result: %d signals, %d slots", int(signal_counter), int(slot_counter));
slot_counter = 0;
}
public slots:
void slot() { ++slot_counter; }
signals:
void signal();
private:
std::atomic_int slot_counter = 0;
std::vector<int> nums{1, 2, 5, 8};
};
#include "main.moc"
int main(int argc, char *argv[]) {
QCoreApplication app(argc, argv);
Foo *foo = new Foo(&app);
QTimer::singleShot(10, foo, [foo, &app]() {
foo->startMapWithWaiting();
foo->startBlockingMap();
app.quit();
});
return app.exec();
}
Output is
startMapWithWaiting
result: 4 signals, 4 slots
startBlockingMap
result: 4 signals, x slots
Where x
varies from 0 to 4 depending on… something. Which is confusing.
I wonder what's the difference between the two ways and how I misread documentation.