I have been trying to generate random number in C++ using rand_r, while using multiple threads for parallel implementation in a pretty big code, which utilizes a lot of seeds. Also, I need to run my simulation multiple times. I want a different random number generated for the same seed in a particular node. However, I keep getting the same sequence (which is understandable due to same initialization of the random generator). Any ideas to reset the random generator? I have explained the question using an example below. I cannot use rand() as it is not thread safe, and I am using an older version of c++ (4.4.7). Also, I generate a hell lot of seeds in one simulation, so kindly do not suggest using a different seed in every simulation.
Example Code:
#include <stdio.h>
#include <mpi.h>
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <stdlib.h>
using namespace std;
int main(int argc, char** argv) {
int rank;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
unsigned int rank2 = rank;
int random_n = rand_r(&rank2);
cout << "Random number is: " << random_n << " in node: " << rank << endl;
return MPI_Finalize();
}
The result generated is:
Random number is: 1012484 in node: 0
Random number is: 476707713 in node: 1
Random number is: 952403967 in node: 2
Random number is: 1430195325 in node: 3
Upon executing the simulation again, I want different random number in the nodes. However, the result I get is:
Random number is: 1012484 in node: 0
Random number is: 476707713 in node: 1
Random number is: 952403967 in node: 2
Random number is: 1430195325 in node: 3
Any help on this would be appreciated!!
Aucun commentaire:
Enregistrer un commentaire