简体   繁体   English

rand() 与 fork() 一起使用时生成相同的数字

[英]rand() generates same numbers when used with fork()

I'm trying to generate random numbers in a specific range.我正在尝试在特定范围内生成随机数。 I'm also using children processes in my program.我也在我的程序中使用子进程。

However, the rand() function generates the same number, say 550, in the for loop even though I have randomized it using srand()但是, rand()函数在 for 循环中生成相同的数字,比如 550,即使我使用srand()对其进行了随机化

Here is the code for demonstration:下面是演示代码:

int main()
{

int count = 5;
int i;
  for (i = 0; i < count; i++)
  {
    pid_t pid = fork();
    if (pid == 0)
    {

      // random number between 500 and 700
      srand(time(NULL));
      int random = rand() % 100 + 500;
      printf("%d\n", random);

      exit(0);
    }
    else
    {

      wait(NULL);
    }
  }

  return 0;
}

Where is the problem?问题出在哪儿? How can I fix that?我该如何解决?

Any help is appreciated.任何帮助表示赞赏。

All of the processes your program is spawning are created very fast, so the value returned by the call time(NULL) is the same for all of them.您的程序生成的所有进程都创建得非常快,因此调用time(NULL)返回的值对于所有进程都是相同的。 It is passed as a seed to the pseudo random number generator, making it to produce the same sequence of pseudo-random numbers for each process.它作为种子传递给伪随机数生成器,使其为每个进程生成相同的伪随机数序列。

In order to get different numbers in each process, you should make sure each process gets a unique seed value.为了在每个进程中获得不同的数字,您应该确保每个进程都获得唯一的种子值。 Simplest way to achieve this would be to add the counter i to the time value:实现这一点的最简单方法是将计数器i添加到时间值:

srand(i + time(NULL));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM