Making asynchronous function calls with QFuture

Published Thursday March 8th, 2007
1 Comment on Making asynchronous function calls with QFuture
Posted in Labs, Qt Concurrent, Threads

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.

Do you like this? Share it
Share on LinkedInGoogle+Share on FacebookTweet about this on Twitter

Posted in Labs, Qt Concurrent, Threads

One comment

Steve Atkins says:

This looks like it would be a really nice idiom for resources other than CPU too. Database connection pools, one connection per worker thread, with either synchronous or asynchronous results, say.

Commenting closed.

Get started today with Qt Download now