Morten
Labs
Threads
Qt Concurrent
Posted by Morten
 in Labs, Threads, Qt Concurrent
 on Thursday, March 08, 2007 @ 15:55

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.

One Response to “Making asynchronous function calls with QFuture”

» Posted by Steve Atkins
 on Wednesday, March 14, 2007 @ 20:12

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.