task_scheduler_init Class extensions

Summary

The task_scheduler_init class is extended with a method to wait for completion of worker threads.

Header

#define TBB_PREVIEW_WAITING_FOR_WORKERS 1
#include "tbb/task_scheduler_init.h"

Syntax

void tbb::task_scheduler_init::blocking_terminate();
bool tbb::task_scheduler_init::blocking_terminate(const std::nothrow_t&) noexcept(true);

Description

The blocking_terminate method of the class task_scheduler_init blocks the calling thread until all worker threads implicitly created by the library have completed. If waiting for thread completion is not safe, e.g. may result in a deadlock, the method fails. The method is overloaded to provide different ways of reporting failure.

Method Description
void tbb::task_scheduler_init::blocking_terminate()

Blocks until all worker threads have completed. Throws a runtime_error if waiting for the completion of worker threads is not safe.

bool tbb::task_scheduler_init::blocking_terminate(const std::nothrow_t&) noexcept(true)

Blocks until all worker threads have completed. Returns true if all worker threads have completed successfully, or false if waiting for the completion of worker threads is not safe.

The following conditions should be met for blocking termination to succeed:

  • No active (i.e. not yet completed) application thread initialized the task scheduler automatically;

  • No active (i.e. not yet terminated) instances of class task_arena exist in the whole program;

  • blocking_terminate is called for each active instance of class task_scheduler_init, possibly by different application threads.

Under these conditions, it is guaranteed that at least one blocking_terminate call succeeds, at which point all worker threads have completed. If calls are done simultaneously by multiple application threads, more than one call might succeed.

Tip

If you know how many active task_scheduler_init instances exist in the program, it is recommended to terminate all but the last one normally, then call blocking_terminate for the last instance.

CAUTION

The method always fails if called inside a task, a parallel algorithm, or a flow graph node.

Example

#define TBB_PREVIEW_WAITING_FOR_WORKERS 1
#include "tbb/task_scheduler_init.h"
#include "tbb/parallel_for.h"

#include <iostream>

int main() {
    tbb::task_scheduler_init init;
    // Do some parallel work here, e.g.
    tbb::parallel_for(0, 10000, [](int){});
    try {
        init.blocking_terminate();
        // Intel TBB worker threads are terminated at this point.
    } catch (const std::runtime_error&) {
        std::cerr << "Failed to terminate the worker threads." << std::endl;
    }
    return 0;
}
For more complete information about compiler optimizations, see our Optimization Notice.