1

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.

steve
  • 133
  • 1
  • 2
  • 10
  • 3
    `std::vector` is not thread-safe (yes, it's a regrettable design decision to have `std::vector` perform space optimization at the cost of breaking the normal `std::vector` interface/guarantees). Let me see if there's a good dupe. – Max Langhof Sep 11 '19 at 14:06
  • 1
    Oh dear, thanks a lot for the quick answer! And I just keep looking for almost two days in the wrong direction. Never questioned `std::vector` to be the problem... – steve Sep 11 '19 at 14:31
  • Yeah, you're not the first and won't be the last to fall victim to this. It's long been recognized as a serious mistake but can't really be changed anymore, that ship has sailed. Sadly. – Max Langhof Sep 11 '19 at 14:52

0 Answers0