The following simple script produce random number in parallel
#include <random>
#include <iostream>
#include <omp.h>
int main(int argc, char *argv[])
{
// Two integers are expected from the command line.
// The first integer is a random seed
// The second integer is the number of threads.
// Read the seed and create the random number generator and the random distribution
int seed = std::stoi(argv[1]);
std::mt19937 mt(seed);
std::uniform_real_distribution<float> dist(0, 100);
// Read the number of threads and set it.
int nbThreads = std::stoi(argv[2]);
omp_set_num_threads(nbThreads);
// Number of random number for demonstration
int n = 2;
// Will store the random number to print them conveniently
std::vector<float> store(n);
// produce 'n' random numbers
#pragma omp parallel for
for (int i = 0 ; i < n ; ++i)
{
store[i] = dist(mt);
}
// print the random numbers
for ( auto& rnd : store )
{
std::cout << rnd << std::endl;
}
return 0;
}
The above script is deterministic when using a single thread (first element is the seed, second element is the number of threads)
./test 3 1
55.0798
7.07249
./test 3 1
55.0798
7.07249
./test 7 1
7.63083
22.7339
./test 7 1
7.63083
22.7339
However, it is partially stochastic and contain correlation between threads (which can be a pretty big issue) when using more than one thread
./test 3 2
43.1925
43.1925
./test 3 2
55.0798
7.07249
./test 7 2
22.7339
7.63083
./test 7 2
7.63083
7.63083
Is it possible to ...
- have deterministic output for a given number of threads?
or even better
- have deterministic output regardless of the number of threads?
Aucun commentaire:
Enregistrer un commentaire