2

I have code where I have to run parallel_for (independent from each other) at once parallely.

Code is something like:

tbb::parallel_for(range1,func1());//first

tbb::parallel_for(range2,func2());//second

tbb::parallel_for(range3,func3());//third

I have tried using task_group. Is there any other method available?

Vibhor
  • 35
  • 6
  • 4
    What *have* you tried? How did your attempt work or fail? Can you perhaps show us a [Minimal, Complete, and Verifiable Example](http://stackoverflow.com/help/mcve) of your attempt? And please [read about how to ask good questions](http://stackoverflow.com/help/how-to-ask). – Some programmer dude Aug 31 '17 at 08:41
  • Why? If the three are large enough, each will saturate your cpus and only modest "rundown"/"runup" wasted cpu will occur if you do it in series, assuming you need all 3 finished to proceed. – Yakk - Adam Nevraumont Aug 31 '17 at 11:32
  • and why do you want another approach if task_group works well? – Anton Aug 31 '17 at 15:34
  • @Anton The "runup" I am getting with task group is marginal. Also I wanted to know which other methods will be suitable for appication like this. – Vibhor Sep 18 '17 at 07:13
  • It's rather not because the choice of task_group. As Yakk mentioned above, check your problem size first or because nobody's remember to warm up threads before starting to measure – Anton Sep 18 '17 at 13:06

2 Answers2

7

There are many ways to run any parallel algorithm in parallel, you want just run it inside another parallel algorithm of your choice. task_group is just one example. The simplest approach for your case is to use parallel_invoke:

tbb::parallel_invoke([]{
        tbb::parallel_for(range1,func1);//first
    }, []{
        tbb::parallel_for(range2,func2);//second
    }, []{
        tbb::parallel_for(range3,func3);//third
    }
);

but one can choose to use another parallel_for over array of ranges and function pointers, or use parallel_pipeline, parallel_for_each, or raw low-level tbb::task.

Anton
  • 6,349
  • 1
  • 25
  • 53
  • You should remember that the scheduling algorithm for tasks in TBB may give you unexpected results. If you want all the tasks will progress at the same rate, you may be disappointed, because TBB uses a greedy (unfair) scheduling algorithm. Your tasks will all complete, and with TBB you won't oversubscribe the system, but they may still complete one-at-a-time. – cahuson Sep 02 '17 at 03:11
  • You could also schedule multiple graph nodes each with a parallel algorithm. – cahuson Sep 02 '17 at 03:15
1

You can put them each in a single std::thread and make a join afterwards. See also also.

schorsch312
  • 5,553
  • 5
  • 28
  • 57