Search code examples
c++tbb

TBB: How to get the current task arena?


I have a small scheduler observer class

namespace
{
    class TestObserver : public tbb::task_scheduler_observer
    {
    public:
        TestObserver(tbb::task_arena& a) : tbb::task_scheduler_observer(a)
        {
            observe(true); // activate the observer
        }

        /*override*/ void on_scheduler_entry(bool worker)
        {
            // Do something here
            std::cout << "on_scheduler_entry: " << tbb::task_arena::current_thread_index() << std::endl;
        }

        /*override*/ void on_scheduler_exit(bool worker) 
        { 
            std::cout << "on_scheduler_exit: " << tbb::task_arena::current_thread_index() << std::endl;
        }
    };
}

And I'd like to initialize it with the current task arena. In my main code, I initialize TBB thusly:

unsigned int numThreads = num_threads;
if (numThreads < 1) numThreads = tbb::task_scheduler_init::automatic;

tbb::task_scheduler_init init(numThreads);

TestObserver obs(...); // <-- fail!

I'd like to initialize the observer with the current task arena. While I don't explicitly initialize one, TBB should do do automatically, right?


Solution

  • Do not use tbb::task_scheduler_init class; it's already deprecated and will eventually be removed. If you need to limit the number of threads globally, use tbb::global_control instead; if you want to limit concurrency for a given job, use tbb::task_arena. In the latter case, you will also have no problem with attaching an observer to it.

    To create an observer for the current task arena, use tbb::task_scheduler_observer(true). The boolean argument is used to distinguish such "local" observer from a "global" one, i.e. not tied to any specific arena (the "global" semantics was the initial one for TBB observers, and it has taken the default constructor).

    You might also create a task_arena object attached to the current arena, and use that for initializing your observer as well as for job submission. For that, construct or initialize the arena with the special argument: tbb::task_arena(tbb::task_arena::attach()).