Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a boost function for parallel_for in C++?

I need to do a parallel_for. Is there an easy implementation of this available in the standard C++ library, or in Boost? I have not found it.

By the way I am using Ubuntu. So I don't want Microsoft libraries.

like image 844
becko Avatar asked Oct 26 '25 03:10

becko


1 Answers

Since C++17 we have most algorithm as potentially parallel versions using the "execution policy" argument: https://en.cppreference.com/w/cpp/algorithm/execution_policy_tag_t

For a simple for-each, the algorithm would befor_each: https://en.cppreference.com/w/cpp/algorithm/for_each

std::vector<int> v = get_tons_of_values();
std::for_each(std::execution::par, std::begin(v), std::end(v), [](int i) {
   work(i);
});

In this example, we "ask" the lambda to be executed in parallel.

Note that the algorithm will decide itself it it will effectively run in parallel and how to run in parallel. For example if there is not enough values to make the cost of running parallel worth it, it will not run in parallel on most implementations. Consult your standard library implementation documentation to learn about the heuristics they will use.

like image 137
Klaim Avatar answered Oct 28 '25 18:10

Klaim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!