c++multithreadingpplparallel.for

Limit number of threads used in Concurrency::parallel_for


How to limit number of threads used in

Concurrency::parallel_for<int>(0, 100, 1, [&](int k) 

I saw the scheduler/task idea, I fail to use it cause inside the parallel for there is a lot of logic and I need to pass arguments, all the examples for tasks is containing only std::cout<<"Hey"<<std::endl; inside the task.

Hope you have some ideas.

bool func1(int x,int y....) //A lot of params{
 Concurrency::parallel_for<int>(0, 100, 1, [&](int k) {
//a lot of logic depends on the input
}
}

Solution

  • I haven't used the interface - but the following might work (assuming 8 workers and parallel for 100 cases - otherwise adjust the 100/8).

    Concurrency::simple_partitioner splitter(100/8);
    Concurrency::parallel_for<int>(0, 100, 1, [&](int k) {
    //a lot of logic depends on the input
    }, splitter);
    

    This does not limit the number of threads directly, but chunk the data achieving the same.

    The idea could also be found on: https://katyscode.wordpress.com/2013/08/17/c11-multi-core-programming-ppl-parallel-aggregation-explained/ https://learn.microsoft.com/en-us/cpp/parallel/concrt/reference/simple-partitioner-class?view=msvc-160 https://learn.microsoft.com/en-us/cpp/parallel/concrt/reference/concurrency-namespace-functions?view=msvc-160#parallel_for