简体   繁体   English

与相同引擎并行生成随机数失败

[英]Generating random numbers in parallel with identical engines fails

I am using the RNG provided by C++11 and I am also toying around with OpenMP. 我正在使用C ++ 11提供的RNG,并且还在玩OpenMP。 I have assigned an engine to each thread and as a test I give the same seed to each engine. 我已经为每个线程分配了一个引擎,并且作为测试,我为每个引擎提供了相同的种子。 This means that I would expect both threads to yield the exact same sequence of randomly generated numbers. 这意味着我希望两个线程都能产生完全相同的随机生成数字序列。 Here is a MWE: 这是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;
}

Most often I get the output 0.857946 0.857946 , but a few times I get 0.857946 0.592845 . 通常,我得到的输出是0.857946 0.857946 ,但有几次我得到的是0.857946 0.592845 How is the latter result possible, when the two threads have identical, uncorrelated engines?! 当两个线程具有相同,不相关的引擎时,后一种结果怎么可能?

You have to put nor and uni inside the omp parallel region too. 您也必须将noruni放在omp parallel区域内。 Like this: 像这样:

#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;

Otherwise there will only be one copy of each, when in fact every thread needs its own copy. 否则,每个线程只有一个副本,而实际上每个线程都需要自己的副本。

Updated to add: I now see that exactly the same problem is discussed in this stackoverflow thread . 更新添加:我现在看到在这个stackoverflow线程中讨论了完全相同的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM