Tutorial : Task Based Programming

Previous : Thread Local Storage Top : Tutorial    Next : Syncronization Primitives

Task Based Programming

The Intel® Threading Building Blocks (Intel® TBB) library provides both a high-level and low-level interface to its task scheduler.   These interfaces can be used when no generic algorithm is provided that exactly matches your needs. The high-level interface, class task_group, lets you easily create groups of potentially parallel tasks from functors or lambda expressions.  The low-level interface, class task, permits more detailed control, such as control over exception propagation and affinity, but is not as user-friendly.

The example below shows a recursive implementation of the calculation of the nth Fibonacci number using a task_group.  This implementation may spawn many tasks in parallel, and is not a scalable solution; it should be considered as a syntactic example only.

    #include "tbb/task_group.h"
    
    using namespace tbb;
    
    int Fib(int n) {
        if( n<2 ) {
            return n;
        } else {
            int x, y;
            task_group g;
            g.run([&]{x=Fib(n-1);}); // spawn a task
            g.run([&]{y=Fib(n-2);}); // spawn another task
            g.wait();                // wait for both tasks to complete
            return x+y;
        }
    }

There are a number of resources available to learn more about the task scheduling features in the Intel® Threading Building Blocks library.

 

Previous : Thread Local Storage Top : Tutorial    Next : Syncronization Primitives