为什么兰特()不是叉经过这么乱? [英] Why is rand() not so random after fork?

查看:103
本文介绍了为什么兰特()不是叉经过这么乱?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main() {
    int i =10;
    /* initialize random seed:  */
    srand(time(NULL));
    while(i--){
        if(fork()==0){
            /* initialize random seed here does not make a difference:
            srand(time(NULL));
             */
            printf("%d : %d\n",i,rand());
            return;
        }
    }
    return (EXIT_SUCCESS);
}

打印同一(不同在每次运行时)数的10倍 - 预期?
我有一个更复杂的一块code,其中每个分叉过程反过来运行 - 没有什么区别

Prints the same (different on each run) number 10 times - expected ? I have a more complicated piece of code where each forked process runs in turn - no difference

推荐答案

输出必须的是相同的。如果两个进程每个种子使用相同的种子随机数和每个呼叫兰特一次,他们的必须的得到同样的结果。这是有一个种子的整点。您所有的流程叫函数srand 使用相同的种子(因为你只叫函数srand 一次),他们所有的呼叫兰特一次,所以它们的必须的得到同样的结果。

The outputs must be the same. If two processes each seed the random number with the same seed and each call rand once, they must get the same result. That's the whole point of having a seed. All of your processes call srand with the same seed (because you only call srand once) and they all call rand once, so they must get the same result.

取消注释函数srand 不会有所作为,因为除非秒数发生了变化,他们还是会给予相同的种子。你可以这样做:

Uncommenting the srand won't make a difference because unless the number of seconds has changed, they will still give the same seed. You could do:

srand(time(NULL) ^ (getpid()<<16));

这篇关于为什么兰特()不是叉经过这么乱?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆