0
#include <pthread.h>
#ifndef __linux__
#include <windows.h>// to include the windows.h library//
#endif
#include <stdio.h>
#include <stdlib.h>
#define NUM_THREADS 5
#include <sys/timeb.h>

void *PrintHello(void *threadid)
{
   srand(time(NULL));
   long tid,a;
   tid = (long)threadid;
   a=rand()%5;
   printf("Hello World! It's me, thread #%ld!%ld\n", tid,a);
   pthread_exit(NULL);
    }

int main (int argc, char *argv[])
{
    pthread_t threads[NUM_THREADS];
    int rc;
    long t,a;
    srand(time(NULL));
    for(t=0; t<NUM_THREADS; t++){
          a=rand()%5;
           printf("In main: creating thread %ld,%ld\n", t,a);
           rc = pthread_create(&threads[t], NULL, PrintHello, (void *)t);
              if (rc){
            printf("ERROR; return code from pthread_create() is %d\n", rc);
                 exit(-1);
       }
       } 

          /* Last thing that main() should do */
      pthread_exit(NULL);
      }

Alright I have this simple code and when I compile it inside the main() the random numbers are different from one another but when i try to generate random numbers inside the threads, all the numbers that are produced are the same.

Izanagi
  • 199
  • 1
  • 2
  • 10
  • Related: http://stackoverflow.com/questions/10159728/does-one-need-to-call-srand-c-function-per-thread-or-per-process-to-seed-the-r – Lior Kogan Dec 06 '12 at 13:52

1 Answers1

0

Try seeding from outside the threads. The problem is that you get the same seed for each thread

klundby
  • 301
  • 1
  • 3
  • 17
  • jeez thanks.To fix this I only had to delete srand(time(NULL)) from the threads and only have this in the main...Thanks again – Izanagi Dec 06 '12 at 13:47