Skip to Main Content
Intel Threading Building Blocks
book

Intel Threading Building Blocks

by James Reinders
July 2007
Intermediate to advanced content levelIntermediate to advanced
332 pages
10h 4m
English
O'Reilly Media, Inc.
Content preview from Intel Threading Building Blocks

Quick Introduction to Lambda Functions

Adding lambda functions to C++ would let a programmer write a loop body in-place instead of having to write a separate STL-style function object. Similar capability is found in the anonymous method in C#, in the inner class in Java, and in the primordial lambda expression of LISP.

For example, currently a programmer who wants to convert a sequential for loop into a parallel_for has to write something like this:

	// Without lambda expression
	class ApplyFoo {
	public:
	    int my_x;
	    ApplyFoo( int x ) : my_x(x) {}
	    void operator()(const blocked_range<size_t>& r) const {
	        for(size_t i=r.begin(); i!=r.end(); ++i)
	            Foo(i,my_x);
	    }
	};
	void ParallelApplyFoo(size_t n, int x) {
	    parallel_for(blocked_range<size_t>(0,n,10),
	                 ApplyFoo(x));
	}

In particular, the programmer has to deal with capturing the value of parameter x in ParallelApplyFoo so that it can be referenced from ApplyFoo. The addition of lambda expressions, as recently proposed to the C++ Standards Committee, would enable the preceding example to be written more concisely as:

	// With lambda expression
	void ParallelApplyFoo(size_t n, int x) {
	    parallel_for(
	        blocked_range<size_t>(0,n,10),
	        <>const blocked_range<size_t>& r) {
	           for(size_t i=r.begin(); i<r.end(); ++i)
	               Foo(i,x);
	          });
	}

The <> directs the compiler to convert the expression after it into a function object that does everything the handcoded ApplyFoo would do. In general, lambda expressions let programmers pass blocks of code as parameters without having ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Intel® Xeon Phi™ Coprocessor Architecture and Tools: The Guide for Application Developers

Intel® Xeon Phi™ Coprocessor Architecture and Tools: The Guide for Application Developers

Rezaur Rahman

Publisher Resources

ISBN: 9780596514808Errata Page