PLease see the whole question
I know that srand()
should be called only once, but my 2nd code segment shows that that does not solve the issue!!!!
The program I have written is giving me outputs which I can't quite make out why is it so. Different alterations of code segments give different outputs.
Objective of code:
The code uses omp
to simply run a piece of code for 3 threads. Each thread has to print 3 random values using the rand()
function. So, a total of 9 outputs would come. Thread 0
is the main thread/ the main program's run flow. Thread 1
and Thread 2
are the fellow new threads created at the start of code for the threads.
The code:
#include<omp.h>
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main()
{
#pragma omp parallel num_threads(3)
{
srand(time(NULL));
int i=0;
for(i=0;i<3;i++)
{
printf("\nRandom number: %d by thread %d", rand(), omp_get_thread_num());
}
}
return 0;
}
The output:
Random number: 17105 by thread 0
Random number: 30076 by thread 0
Random number: 21481 by thread 0
Random number: 17105 by thread 1
Random number: 30076 by thread 1
Random number: 21481 by thread 1
Random number: 17105 by thread 2
Random number: 30076 by thread 2
Random number: 21481 by thread 2
But if I make keep the srand(time(NULL))
before the code for thread like,
srand(time(NULL));
#pragma omp parallel num_threads(3)
{
int i=0;
......
......(rest is same)
The output is,
The output:
Random number: 16582 by thread 0
Random number: 14267 by thread 0
Random number: 14030 by thread 0
Random number: 41 by thread 1
Random number: 18467 by thread 1
Random number: 6334 by thread 1
Random number: 41 by thread 2
Random number: 18467 by thread 2
Random number: 6334 by thread 2
The Problem, and my doubts:
- By placing the `srand` outside, all the threads' 1st call to `rand()` gave the same random number, all of their 2nd call gave the same random number, and similarly for their 3rd call also.
- By placing the `srand` inside, the main thread's calls resulted in different random numbers than the others. BUT, the 2 new other threads among them gave the same random number for their respective calls to `rand()`.
So,
- What is actually happening here? How come the placement of the `srand()` function make a difference only to the main thread (thread `0`)?
- Why is it that either ways the the other 2 new threads always output same random number for the respective call to `rand()`?
- How is this `srand()` and `rand()` even linked, to cause this abnormality?
- And I tried giving wait intervals to each thread to remove that possibility of the `rand()` function being called by different threads at the same time, which might result in same random number maybe. But the problem was exactly like before. No change in the output (just the time at which output occurred was different).
Please help me understand this whole thing..