my question is: why is this code not thread safe?
#include "pstl/algorithm"
#include "pstl/execution"
#include <iostream>
#include <random>
#include <vector>
struct SomeData {
double x;
double x_max;
};
std::vector<SomeData> generateSample() {
std::vector<SomeData> data;
std::mt19937 rand(1234);
std::uniform_real_distribution<double> uniform(0.0, 1.0);
for (unsigned int i = 0; i < 1000; ++i) {
data.push_back({uniform(rand), 0.5});
}
return data;
}
int main() {
auto sample = generateSample();
for (size_t i = 0; i < 20; ++i) {
std::vector<bool> result(sample.size());
std::transform(pstl::execution::par, sample.begin(), sample.end(),
result.begin(), [](const SomeData &d) {
if (d.x > d.x_max) {
return true;
}
return false;
});
size_t above_max(0);
for (auto x : result) {
if (x)
++above_max;
}
std::cout << "above max: " << above_max << "\n";
}
}
If you run this with pstl::execution::par
, it will give different results. If you run it with ::seq
or ::unseq
, the results are the same.
I'm totally puzzled to why this is not thread safe, since the function just processes independent objects and gives back some value.