openMP使用相同的种子生成不同的随机数

时间:2014-01-03 23:23:24

标签: c++ openmp srand

我是openMP的新手,在我的程序中需要复杂的模拟,重复结果,为每个模拟设置种子,但是,在实现openMP时,每次运行它都会产生不同的结果。所以我写了一个简单的例子来检查问题如下, 我每次都会产生不同的结果:

#include <iostream>
#include <omp.h>
using namespace std;


int main () {

double A[10];

#pragma omp parallel for
for( int i=0;i<10;i++){
    srand(i+1);
    int m = rand()%100;
    A[i] = m;
}

cout<<"A= \n";

for(int i=0;i<10;i++){
    cout<<i<<" "<<A[i]<<" \n";
}
   return 0;
}

我跑了两次,结果是: A = 0 86 1 25 2 78 3 1 4 46 5 95 6 77 7 83 8 15 9 8

和 A = 0 15 1 41 2 65 3 1 4 75 5 85 6 95 7 83 8 74 9 8

非常感谢!

2 个答案:

答案 0 :(得分:2)

rand()使用静态并且不是线程安全的。您需要使用不同的,线程安全的PRNG。请参阅Thread-safe random number generation for Monte-Carlo integrationDo PRNG need to be thread safe?

答案 1 :(得分:1)

这是一个错误

A[i] += m;

您正在阅读从未分配的A[i]的先前值。这是未定义的行为。尝试

A[i] = m;

然后,请注意随机数状态可能不是threadlocal。获得更好的RNG,你有一个显式的状态变量,而不是访问共享的全局状态。