Calling rand/mt_rand on forked children yields identical results

前端 未结 2 856
一整个雨季
一整个雨季 2021-01-20 05:30

I\'m writing a script that needs to execute concurrent tasks in PHP.

I ran a little test and ran into strange result. I\'m using pcntl_fork to generate a child. The

2条回答
  •  独厮守ぢ
    2021-01-20 06:10

    That is because all children start with the same state (fork() duplicates the code and data segments). And since rand and mt_rand are pseudorandom generators, they will all generate the same sequence.

    You will have to re-initialize the random generator, for example with the process/thread ID or read a few bytes from /dev/urandom.

提交回复
热议问题