Rand()函数在线程中

时间:2012-12-06 13:21:36

标签: multithreading pthreads srand

#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);
      }

好吧,我有这个简单的代码,当我在main()中编译随机数时 是不同的,但当我尝试在线程内生成随机数时,生成的所有数字都是相同的。

1 个答案:

答案 0 :(得分:0)

尝试从线程外部播种。问题是你为每个线程获得相同的种子