Intel Threading Building Blocks

CS 441 Lecture, Dr. Lawlor

Intel's Threading Building Blocks (TBB) is a C++ library designed to make it easy to write high-performance parallel code.  The idea is that the TBB runtime system takes care of creating threads and balancing load, so your application is smaller and simpler.

Intel is doing this because there's still not much multicore software out there.

Here's a simple example program, now runnable in NetRun.  Note that this program takes about twice as long using only 1 thread, which means TBB has done a good job of balancing the load.
#include "tbb/task_scheduler_init.h"
#include "tbb/parallel_for.h"
#include "tbb/blocked_range.h"

class my_task {
public:
void operator() (const tbb::blocked_range<int> &r) const {
int a=r.begin();
int b=r.end();
for (int i=a;i<b;i++) {
volatile int sum=0; /* note to compiler: just do it, OK? */
for (int j=0;j<1000*1000;j++) {sum++;}
}
std::cout<<"Task: "<<a<<" .. "<<b<<" on "<<(void *)this<<"\n";
}
};

int foo(void)
{
double start_time=time_in_seconds();
int nthreads=2; /* number of threads for TBB to create (-1 for auto) */
tbb::task_scheduler_init init(nthreads);
my_task parent;
int start=0, stop=100;
tbb::parallel_for (tbb::blocked_range<int>(start, stop),
parent, tbb::auto_partitioner());
double elapsed_time=time_in_seconds()-start_time;
std::cout<<"That took "<<elapsed_time<<" seconds\n";
return 0;
}

(executable NetRun link)