随机数生成器rand(3)使用全局状态变量(隐藏在(g)libc实现中)。从多个线程访问它们会导致缓存问题,而且也不安全。您应该对线程rand_r(3)使用seed参数private 的调用:
long i;
unsigned seed;
#pragma omp parallel private(seed)
{
// Initialise the random number generator with different seed in each thread
// The following constants are chosen arbitrarily... use something more sensible
seed = 25234 + 17*omp_get_thread_num();
#pragma omp for
for (i = 0; i <= 1000000000; i++) {
double x = rand_r(&seed);
}
}
请注意,并行执行与串行执行时会产生不同的随机数流。我还建议将其erand48(3)作为更好的(伪)随机数源。