lundi 30 janvier 2017

Function using rand_r() in a source file and multithreading

I have a source file in which I defined a function to fill a vector with random 1 or 0, something like:

int rand_range(int lo, int hi) {
 return lo + rand_r(&seed) % (hi - lo);
}
//fill a vector with n 1 and N-n 0 at random
void random_fill(int vec[], int dim, int n) {
 int i;
 //the condition is n!=0!
 for (i = 0; n; ++i) {
  if (rand_range(0, dim-i) < n) {
   vec[i] = 1;
   --n;
 }
 else
   vec[i] = 0;
 }
 for (; i < dim; ++i) vec[i] = 0;
}

seed is a variable declared in the same source file.

In my main.c file I use openmp() to parallelize my program, but I have to call this function in every thread. If I simply call:

random_fill(vec, dim, n);

inside the parallelized area, do I get issues? What's the most correct way to call a function that generates and works with random numbers in a thread safe way?




Aucun commentaire:

Enregistrer un commentaire