QtConcurrent-simple-usage: Difference between revisions

From Qt Wiki
Jump to navigation Jump to search
(Add "cleanup" tag)
(Decode HTML entity names)
Line 27: Line 27:
{
{
  QList<Params> params = generateParamsSet();
  QList<Params> params = generateParamsSet();
  QList<Result> results = QtConcurrent::blockingMapped( params, &amp;Optimizer::calculateStats );
  QList<Result> results = QtConcurrent::blockingMapped( params, &Optimizer::calculateStats );
  …
  …
}
}


Result Optimizer::calculateStats( const Params &amp;params )
Result Optimizer::calculateStats( const Params &params )
{
{
  return someReallyTimeConsumingFunction( params ); //this function returns the Result object.
  return someReallyTimeConsumingFunction( params ); //this function returns the Result object.
Line 46: Line 46:
  QList<Result> results;
  QList<Result> results;
  #ifndef QT_NO_CONCURRENT
  #ifndef QT_NO_CONCURRENT
  results = QtConcurrent::blockingMapped( params, &amp;Optimizer::calculateStats );
  results = QtConcurrent::blockingMapped( params, &Optimizer::calculateStats );
  #else
  #else
  for( int i = 0; i < params.size();''+i ) {
  for( int i = 0; i < params.size();''+i ) {

Revision as of 17:44, 12 March 2015

This article may require cleanup to meet the Qt Wiki's quality standards. Reason: Auto-imported from ExpressionEngine.
Please improve this article if you can. Remove the {{cleanup}} tag and add this page to Updated pages list after it's clean.

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:

void Optimizer::execute()
{
 QList<Params> params = generateParamsSet();
 QList<Result> results;
 for( int i = 0; i < params.size(); +''i ) {
 results.append( someReallyTimeConsumingFunction(params) );
 }

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

void Optimizer::execute()
{
 QList<Params> params = generateParamsSet();
 QList<Result> results = QtConcurrent::blockingMapped( params, &Optimizer::calculateStats );
 
}

Result Optimizer::calculateStats( const Params &params )
{
 return someReallyTimeConsumingFunction( params ); //this function returns the Result object.
}

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: void Optimizer::execute() {

QList<Params> params = generateParamsSet();
QList<Result> results;
#ifndef QT_NO_CONCURRENT
results = QtConcurrent::blockingMapped( params, &Optimizer::calculateStats );
#else
for( int i = 0; i < params.size();+i ) {
results.append( someReallyTimeConsumingFunction(params) );
}
#endif

… }