I am writing some library code in C++, and I need to generate some random numbers. I created the function below to generate a per thread generator and initialize it using data from std::random_device. If I call it in a single-threaded environment, everything seems to work. However, if I call it concurrently I seem to get repeated elements.
inline std::mt19937_64& initialize_mt_generator() {
constexpr size_t state_size = std::mt19937_64::state_size *
std::mt19937_64::word_size / 32;
std::vector<uint32_t> random_data(state_size);
thread_local std::random_device source{};
std::generate(random_data.begin(), random_data.end(), std::ref(source));
thread_local std::seed_seq seeds(random_data.begin(), random_data.end());
thread_local static std::mt19937_64 engine(seeds);
return engine;
}
The way that I am using it is this function is in a library, that I use to make a Python extension. The parallel code is entirely in Python where I use the multiprocessing module. I am not sure that that matters through.
Aucun commentaire:
Enregistrer un commentaire