Search code examples
c++multithreadingtasktbb

Threading Building Blocks spawn nested tasks


Hello everybody I got following idea:

I have a manager task which spawns a phase1 task and afterwards there should be the execution of a phase2 task.

I got following code :

execute(){

    set_ref_count(3);
    task* one = new (allocate_child())phase1_task();
    one->set_ref_count(2);
    task*two = new (one->allocate_child())phase2_task();
    spawn(*one);    

    wait_for_all();
    return 0;
}

But somehow I still encounter a problem with the refcounter ... Can somebody help me ?


Solution

  • If I understand you correctly, for each phase-1 task you want then execute exactly one phase-2 task. Then you need this:

    set_ref_count(5); // for 4 child tasks, plus 1 for waiting
    
    for (int i = 0; i< 4; i++) {
        task* two = new (allocate_child()) phase2_task(ctx, iteration, i);
        two->set_ref_count(1); // for a single child task
        task* one = new (two->allocate_child()) phase1_task(ctx, iteration, i);
        spawn(*one);
    }
    
    wait_for_all();
    

    The logic is that a "parent" task gets control after all its "child" tasks complete. So you want to spawn phase-1 tasks, but first make phase-2 tasks their "parent", not vice versa.

    As for the reference counter: for a parent task, set as many references as there will be child tasks, and add 1 if the parent task already executes and will call wait_for_all(), to make sure that its reference count does not go to 0 and it will not execute for second time.