Intel® Threading Building Blocks (Intel® TBB) provides common parallel algorithm patterns in the form of function templates. These templates often require passing in snippets of code as function objects. C++0x lambda expressions simplify writing such function objects. Therefore, Intel® TBB and C++0x lambda expressions are a powerful combination for parallelizing code.
For more information on Intel® TBB, see the Intel® TBB documentation.
Consider the following serial code:
void SerialApplyFoo( float b[], const float a[], size_t n ){
for( size_t i=0; i<n; ++i )
b[i] = Foo(a[i]);
}
If it is safe to execute the iterations in parallel, you can rewrite the loop using Intel® TBB and a lambda expression:
void ParallelApplyFoo (float b[], const float a[], size_t n){
tbb::parallel_for (size_t(0), n, [=](size_t i) {
b[i] = Foo(a[i]);
});
}
You can also use Lambda expressions with the range-based algorithms in Intel® TBB. Here, the previous example is expressed in range form:
void ParallelApplyFoo (float b[], const float a[], size_t n){
tbb::parallel_for(
tbb::blocked_range<size_t>(0,n),
[=](tbb::blocked_range<size_t> r) {
for (size_t i=r.begin(); i!=r.end(); ++i)
b[i] = Foo(a[i]);
});
}
Both examples can be written using C++ conforming to standard ISO/IEC 14882:1998 (known as C++98). This requires manually crafting function objects for the body of the loop. The examples are simpler to write using lambda expressions, which rely on the compiler to do the tedious crafting.
Copyright © 1996-2011, Intel Corporation. All rights reserved.