Initializing and Terminating the Library
Intel Threading Building Blocks components are defined in the tbb namespace. For brevity’s sake, the namespace is explicit in the first mention of a component in this book, but implicit afterward.
Any thread that uses an algorithm template from the library or the task scheduler must have an initialized tbb::task_scheduler_init object. A thread may have more than one of these objects initialized at a time. The task scheduler shuts down when all task_scheduler_init objects terminate. By default, the constructor for task_ scheduler_init does the initialization and the destructor does the termination. Thus, declaring a task_scheduler_init in main(), as in Example 3-1, both starts and shuts down the scheduler.
Example 3-1. Initializing the library
#include "tbb/task_scheduler_init.h"
using namespace tbb;
int main() {
task_scheduler_init init;
...
return 0;
}The using directive in the example enables you to use the library identifiers without having to write out the namespace prefix tbb before each identifier. The rest of the examples assume that such a using directive is present.
Automatic startup/shutdown was not implemented because, based on Intel’s experience in implementing OpenMP, we knew that parts are too problematic on some operating systems to do it behind the scenes. In particular, always knowing when a thread shuts down can be quite problematic.
Calling the initialization more than once will not cause the program to fail, but it is a bit ...