The wiki is in the process of moving to wiki.qt.io. Please make your edits there.

QtConcurrent simple usage | Qt Wiki | Qt Project

Hello,

This code focuses on the following problem:
We have a QList<Params>
We need to run some time consuming function for each Params set on the list.

The single core solution:

  1. void Optimizer::execute()
  2. {
  3.   QList<Params> params = generateParamsSet();
  4.   QList<Result> results;
  5.   for( int i = 0; i < params.size(); ++i ) {
  6.     results.append( someReallyTimeConsumingFunction(params) );
  7.   }
  8. ...

Let’s use QtConcurrent to scale easily over the cores!

  1. void Optimizer::execute()
  2. {
  3.   QList<Params> params = generateParamsSet();
  4.   QList<Result> results = QtConcurrent::blockingMapped( params, &Optimizer::calculateStats );
  5.   ...
  6. }
  7.  
  8. Result Optimizer::calculateStats( const Params &params )
  9. {
  10.   return someReallyTimeConsumingFunction( params ); //this function returns the Result object.
  11. }

Using it that way, we are sure that none of the cores is bored during our processing!

To make sure that our code always compiles, even when QtConcurrent is not supported, we may write something like this:

  1. void Optimizer::execute()
  2. {
  3.   QList<Params> params = generateParamsSet();
  4.   QList<Result> results;
  5.   #ifndef QT_NO_CONCURRENT
  6.   results = QtConcurrent::blockingMapped( params, &Optimizer::calculateStats );
  7.   #else
  8.   for( int i = 0; i < params.size(); ++i ) {
  9.     results.append( someReallyTimeConsumingFunction(params) );
  10.   }
  11.   #endif
  12. ...
  13. }

Categories: