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

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

4

1 回答 1

0

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

于 2012-12-06T13:28:01.593 回答