Here there is an example code with a std::atomic and a std::for_each. (C++ 17)
#include <iostream>
#include <atomic>
#include <vector>
#include <algorithm>
#include <execution>
int main()
{
constexpr int vec_size = 2000000;
std::vector<double> numbers(vec_size, 1.0);
numbers[vec_size / 2] = 2.0;
std::atomic<double> max_value{ 0.0 };
std::for_each(std::execution::par_unseq, numbers.begin(), numbers.end(), [&max_value](double s) {
if (s > max_value)
{
max_value = s;
}
});
std::cout << "Max Value: " << std::fixed << max_value;
return 0;
}
The condition could be evaluated by one thread, during that, another thread could update the max_value. How to do that correct?
I found this answer from 2013 and I wonder whether this is available built-in with C++17 or C++20 today.