Making asynchronous function calls with QFuture

QtConcurrent::run() runs a function in a worker thread. It returns a QFuture, which is then used to synchronize with the result:

QString foo();
QFuture<QString> f = QtConcurrent::run(foo);
QString string = f.result()

Calling f.result() will block the current thread until foo() has returned. The QFuture template argument must match the return type of foo().

If the function you want to run takes arguments, use QtConcurrent::bind to supply values for them:

QString foo(const QString &string);
QFuture<QString> f = QtConcurrent::run(QtConcurrent::bind(foo, QLatin1String("Hello World")));

qDebug() < < f.result();

(bind is based on the excellent boost::bind package.)

It's usually not a good idea to block the GUI thread to wait for results, so when writing GUI applications it's possible to use signals and slots instead. The QFutureWatcher class is used to make the connections:

QFutureWatcher *watcher  = new QFutureWatcher();
QObject::connect(watcher, SIGNAL(resultReady(const QVariant&)), myObject, SLOT(handleResult(const QVariant &)));

QString foo();
QFuture<QString> f = QtConcurrent::run(foo);

When foo() returns, QFutureWatcher calls the handleResult slot using a queued signal-slot connection.

Blog Topics: