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 に答える