我正在使用C++ 11提供的RNG,我也在使用OpenMP.我为每个线程分配了一个引擎,作为测试,我给每个引擎提供相同的种子.这意味着我希望两个线程产生完全相同的随机生成数字序列.这是一个MWE:
#include <iostream>
#include <random>
using namespace std;
uniform_real_distribution<double> uni(0, 1);
normal_distribution<double> nor(0, 1);
int main()
{
#pragma omp parallel
{
mt19937 eng(0); //GIVE EACH THREAD ITS OWN ENGINE
vector<double> vec;
#pragma omp for
for(int i=0; i<5; i++)
{
nor(eng);
vec.push_back(uni(eng));
}
#pragma omp critical
cout << vec[0] << endl;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我经常得到输出0.857946 0.857946,但有几次得到0.857946 0.592845.当两个线程具有相同的,不相关的引擎时,后一个结果怎么可能?!
你必须放入nor和uni放入该omp parallel地区.像这样:
#pragma omp parallel
{
uniform_real_distribution<double> uni(0, 1);
normal_distribution<double> nor(0, 1);
mt19937 eng(0); //GIVE EACH THREAD ITS OWN ENGINE
vector<double> vec;
Run Code Online (Sandbox Code Playgroud)
否则每个只有一个副本,实际上每个线程都需要自己的副本.
更新以添加:我现在看到在此stackoverflow线程中讨论了完全相同的问题 .
| 归档时间: |
|
| 查看次数: |
1121 次 |
| 最近记录: |