Tuesday, 15 September 2015

php - Calling rand/mt_rand on forked children yields identical results -



php - Calling rand/mt_rand on forked children yields identical results -

i'm writing script needs execute concurrent tasks in php.

i ran little test , ran unusual result. i'm using pcntl_fork generate child. parent process nil wait kid complete.

i'm generating 5 children, each kid runs function generates random number (of seconds) , sleeps long. reason - children generate same number.

here's code example:

private $_child_count = 0; private function _fork_and_exec($func) { $cid = ++$this->_child_count; $pid = pcntl_fork(); if ($pid){ // parent homecoming $pid; } else { // kid $func($cid); //pcntl_waitpid(-1, $status); exit; } } public function parallel_test() { $func = function($id){ echo 'child ' . $id . ' starts'."\n"; $wait_time = mt_rand(1,4); echo 'sleeping '.$wait_time."\n"; sleep($wait_time); echo 'child ' . $id . ' ends'."\n"; }; $children = []; ($i=0; $i<5; $i++){ $children[] = $this->_fork_and_exec($func) ."\n"; } pcntl_wait($status); echo 'done' ."\n"; exit; }

example output:

child 1 starts sleeping 1 kid 2 starts sleeping 1 kid 3 starts sleeping 1 kid 4 starts sleeping 1 kid 5 starts sleeping 1 kid 1 ends kid 2 ends kid 3 ends kid 4 ends kid 5 ends done

thanks in advance

that because children start same state (fork() duplicates code , info segments). , since rand , mt_rand pseudorandom generators, generate same sequence.

you have re-initialize random generator, illustration process/thread id or read few bytes /dev/urandom.

php random fork

No comments:

Post a Comment