QtConcurrent-simple-usage

From Qt Wiki
Revision as of 10:55, 24 February 2015 by Maintenance script (talk | contribs)
Jump to navigation Jump to search


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:

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


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


<br />void Optimizer::execute()<br />{<br /> QList&amp;lt;Params&amp;gt; params = generateParamsSet();<br /> QList&amp;lt;Result&amp;gt; results = QtConcurrent::blockingMapped( params, &amp;Optimizer::calculateStats );<br /> <br />}
<br />Result Optimizer::calculateStats( const Params &amp;params )<br />{<br /> return someReallyTimeConsumingFunction( params ); //this function returns the Result object.<br />}<br />


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&lt;Params&gt; params = generateParamsSet();
QList&lt;Result&gt; 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

}