2 回答

TA贡献1906条经验 获得超10个赞
随机数生成器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)作为更好的(伪)随机数源。

TA贡献1829条经验 获得超7个赞
rand()
是一个外部库函数。它的声明stdlib.h
绝不会说明它是否修改了外部状态,此外,其代码还隐藏在已编译的库中。GCC __atribute__ ((pure))
为纯外部功能提供了显式注释。只需尝试在启用最大优化的情况下编译串行版本,然后自己看看。
添加回答
举报