如何确保std :: mt19937使用boost :: mpi [duplicate]

问题描述 投票:0回答:1

我有一个很大的并行应用程序,在该应用程序中,我需要生成可再现的伪随机数。谁能解释为什么下面的最小示例每次都不生成相同的数字?

省略行“ cout <

//compile: mpic++ -Wall mpi_rng_test.cpp -o mpi_rng_test -lboost_mpi -lboost_serialization
//run: mpirun -np 4 ./mpi_rng_test

#include <boost/mpi.hpp>
#include <iostream>
#include <vector>
#include <cstdlib>
#include <string>
#include <random>

#define LOOPS 1000

namespace mpi = boost::mpi;
using namespace std;
mt19937 rng;

int main(int argc, char* argv[])
{
   mpi::environment env(argc, argv);
   mpi::communicator world;

   if (world.rank() == 0) {
      rng.seed(1);
      for (int m = 0; m <= LOOPS; m++){
         string my_string = "MAIN";
         for (int proc = 1; proc < world.size(); ++proc){
            string outmessage = to_string(m);
            world.send(proc, 0, outmessage);
         }
         vector<string> all_strings;
         gather(world, my_string, all_strings, 0);

         uniform_real_distribution<double> disR0(0.0, 1.0);
         uniform_int_distribution<int> disI1(0, 10000);
         for (int i = 0; i < LOOPS; i++)
            if (disR0(rng) < 0.5)
               cout << disI1(rng) << endl;
      }
   }
   else {
      string inmessage;
      while(inmessage.compare(to_string(LOOPS)) != 0){
         world.recv(0,0,inmessage);
         cout << "PROC" << endl;
         gather(world, to_string(world.rank()), 0);
      }
   }
   return 0;
}

在Linux中,我通过在终端上运行此数字序列来测试数字序列是否可再现:

mpirun -np 4 ./mpi_rng_test | grep -v PROC > a
mpirun -np 4 ./mpi_rng_test | grep -v PROC > b
diff a b

diff的输出:

9312c9312
< 5996
---
> 6
19941c19941
< 3088
---
> 
31896c31896
< 7946
---
> 
43912c43912
< 9596
---
> 96
55140c55140
< 571
---
>
c++ random mpi
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.