Back to Blog home

Making asynchronous function calls with QFuture

Published on Thursday March 08, 2007 by admin in Labs Qt Concurrent Threads | Comments

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);
watcher->setFuture(f);

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

Subscribe to Our Blog

Stay up to date with the latest marketing, sales and service tips and news.

The blog comment system has been migrated to a new platform. If you face any issues, please let us know via feedback@qt.io.