0

I want to create a 1D array of size (10^7) and want to populate it randomly. Is it possible to create many 10 arrays each of size 10^6, populate them randomly and later merge them into one array using OpenMP?

std::random_device rd{};
std::mt19937 rng{rd()};
std::bernoulli_distribution distribution(p);
int array_size = 10000000, N = 50;
array = new uint64_t[array_size];
#pragma omp parallel 
{
    #pragma omp parallel for
    for(int i = 0; i < (array_size); i++){
        uint64_t rn = 0;
        for(int j = 0; j < N; j++){
            rn = ((rn<<1)+(distribution(rng)?1:0));
        }
        array[i] = rn;
    }
}
ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
  • 1
    There are a few posts on Stackoverflow that discuss aspects of using random-number geneerators with OpenMP code. E.g., https://stackoverflow.com/questions/15504264/boost-random-and-openmp. – Michael Klemm Jul 02 '19 at 04:51
  • You will need thread local RNG instances for this. Note that mt19937 is not really meant for parallel execution, so either use different seeds for the different RNGs and hope for the bast or use an RNG that is meant for parallel execution. – Ralf Stubner Jul 02 '19 at 09:04

1 Answers1

-2

As it is an array, simply putting the random assignment in a parallel for section will do the work. OpenMP library will take care of executing paralelly.

std::random_device rd{};
std::mt19937 rng{rd()};
std::bernoulli_distribution distribution(p);
int array_size = 10000000, N = 50;
array = new uint64_t[array_size];
#pragma omp parallel for firstprivate(array_size)
{
    for(int i = 0; i < (array_size); i++)
        array[i] = rn;
}
Atanu Barai
  • 115
  • 7
  • That's not the same function. I understand the OP wants to have random numbers across the array and not the same random number assigned to each array element. – Michael Klemm Jul 02 '19 at 04:38
  • Besides that ... declaring `private(array_size)` seems like a really bad idea. Private variables are *uninitialized*. – Zulan Jul 02 '19 at 08:07