In C++11 there are a bunch of new Random number generator engines and distribution functions. Are they thread safe? If you share a single random distribution and engine amon
The standard (well N3242
) seems to make no mention of random number generation being race free (except that rand
isn't), so it isn't(unless I missed something). Besides there is really no point in having them threadsave, since it would incur a relatively hefty overhead (compared to the generation of the numbers itself at least), without really winning anything.
Furthermore I don't really see a benefit og having one shared random number generator, instead of having one per thread, each being slighly differently initialized (e.g. from the results of another generator, or the current thread id). Afterall you probably don't rely on the generator generating a certain sequence each run anyways. So I would rewrite your code as something like this (for openmp
, no clue about libdispatch
):
void foo() {
#pragma omp parallel
{
//just an example, not sure if that is a good way too seed the generation
//but the principle should be clear
std::mt19937_64 engine((omp_get_thread_num() + 1) * static_cast(system_clock::to_time_t(system_clock::now())));
std::uniform_real_distribution zeroToOne(0.0, 1.0);
#pragma omp for
for (int i = 0; i < 1000; i++) {
double a = zeroToOne(engine);
}
}
}