【问题标题】:Rand() function in threads线程中的 Rand() 函数
【发布时间】:2012-12-06 13:21:35
【问题描述】:
#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() 中编译它时,随机数 彼此不同,但是当我尝试在线程内生成随机数时,生成的所有数字都是相同的。

【问题讨论】:

标签: multithreading pthreads srand


【解决方案1】:

尝试从线程外播种。问题是每个线程都得到相同的种子

【讨论】:

  • 天哪,谢谢。要解决这个问题,我只需要从线程中删除 srand(time(NULL)) 并且只在主线程中使用它...再次感谢
猜你喜欢
  • 2012-01-07
  • 1970-01-01
  • 2014-11-05
  • 2012-11-08
  • 2023-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多