O'Reilly logo

Intel Threading Building Blocks by James Reinders

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

parallel_for Examples

The use of parallel_for is pretty straightforward. The first three examples in this section help you make sure you’re comfortable with Threading Building Blocks basics. The last two examples, ParallelMerge and SubstringFinder, are a little more challenging and will help drill home how versatile parallel_for can be. The next section implements John Conway’s Game of Life and is the only example to mix C++ and managed C++ in this chapter. Chapter 3 covers parallel_for in detail.

ParallelAverage

ParallelAverage defines a routine named ParallelAverage that sets output[i] to the average of input[i-1], input[i], and input[i+1], for 0 ≤ i < n .

Example 11-1. ParallelAverage

#include "tbb/parallel_for.h"
#include "tbb/blocked_range.h"

using namespace tbb;

class Average {
public:
    float* input;
    float* output;
    void operator()( const blocked_range<int>& range ) const {
        for( int i=range.begin(); i!=range.end(); ++i )
            output[i] = (input[i-1]+input[i]+input[i+1])*(1/3.0f);
    }
};

// Note: The input must be padded such that input[-1] and input[n]
// can be used to calculate the first and last output values.
void ParallelAverage( float* output, float* input, size_t n ) {
    Average avg;
    avg.input = input;
    avg.output = output;parallel_for( blocked_range<int>( 0, n, 1000 ), avg );
}

Seismic

Here is a simple seismic wave simulation (wave propagation) based on parallel_for and blocked_range. The key parts of this example are shown here; the entire code is available for download.

The main program ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required