0

I work in a Windows environment (Visual Studio 2019). I want to create a c++ application that has to perform many times: let's say 10000 times. I want to implement this using multiple threads and, of coursem I want to limit the number of the concurrent threads let's say 20. In other words I want to do the same thing that in a c# application I can easy do with the parallel instruction:

public class Program
{
    private static void Main(string[] args)
    {      
       ParallelOptions opt = new ParallelOptions();
       opt.MaxDegreeOfParallelism = 20;
        Parallel.For(0, 10000, opt, i =>
        {
            // Do the task
        });
    }
}
Alessandro Ciurlo
  • 102
  • 1
  • 2
  • 11
  • Look at [std::for_each](https://en.cppreference.com/w/cpp/algorithm/for_each) and use execution policy `std::execution::par`. I'll create a "good" amount of threads. – Ted Lyngmo May 15 '19 at 12:56
  • Take a look at OpenMP. – Michał Walenciak May 15 '19 at 12:59
  • Create a concurrent queue with work items and spawn 20 threads that pull work off the queue. If the queue is empty, have the threads exit. – Botje May 15 '19 at 13:03
  • 1
    https://stackoverflow.com/questions/15752659/thread-pooling-in-c11 is a very relevant answer for this question, too. – Botje May 15 '19 at 13:06
  • 1
    The optimal degree of parallelism can be determined by calling `std::thread::hardware_concurrency()`. Just create a pool of that many threads and a work queue (with a mutex). – rustyx May 15 '19 at 13:07
  • "_optimal_" differs though. Sometimes it's one thread less than `hardware_concurrency()` and sometimes it may be bigger than that. – Ted Lyngmo May 15 '19 at 13:11

1 Answers1

0

The C++ version would probably look like this:

std::vector<workpackage> workpackages;

std::for_each(std::execution::par, workpackages.begin(), workpackages.end(), [](auto& wp) {
    // work with workpackage "wp" here
});

... but you can't decide how many threads it'll use. If you want more control you can create threads manuallly with std::thread and just count how many you have running.

Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108