The code is as follows:
#include<omp.h>
#include<stdio.h>
#include<stdlib.h>
int main()
{
unsigned int seed = 1;
int n =4;
int i = 0;
#pragma omp parallel for num_threads(4) private(seed)
for(i=0;i<n;i++)
{
int temp1 = rand_r(&seed);
printf("\nRandom number: %d by thread %d\n", temp1, omp_get_thread_num());
}
return 0;
}
The code output is:
Random number: 1905891579 by thread 0
Random number: 1012484 by thread 1
Random number: 1012484 by thread 2
Random number: 1012484 by thread 3
This is strange for me: why thread 0 has different number? But when I change n with a const number 4:
#include<omp.h>
#include<stdio.h>
#include<stdlib.h>
int main()
{
unsigned int seed = 1;
const int n =4;
int i = 0;
#pragma omp parallel for num_threads(4) private(seed)
for(i=0;i<n;i++)
{
int temp1 = rand_r(&seed);
printf("\nRandom number: %d by thread %d\n", temp1, omp_get_thread_num());
}
return 0;
}
The code output is:
Random number: 1012484 by thread 2
Random number: 1012484 by thread 3
Random number: 1012484 by thread 0
Random number: 1012484 by thread 1
All threads have the same random numbers. I don't understand the reason that thread 0 has different number when n is not a const variable. Is there any one know this thing? Thanks a lot.