Created
November 5, 2014 10:03
-
-
Save nicklasos/019410f5cfe85ab974e9 to your computer and use it in GitHub Desktop.
php parallel fork
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
define('PROCESSES_NUM', 6); | |
/** | |
* @param array $arr | |
* @param callable $func | |
*/ | |
function parallelForeach(array $arr, callable $func) | |
{ | |
$pid = null; | |
for ($proc_num = 0; $proc_num < PROCESSES_NUM; $proc_num++) { | |
$pid = pcntl_fork(); | |
if ($pid < 0) { | |
fwrite(STDERR, "Cannot fork\n"); | |
exit(1); | |
} | |
if ($pid == 0) break; | |
} | |
if ($pid) { | |
for ($i = 0; $i < PROCESSES_NUM; $i++) { | |
pcntl_wait($status); | |
$exitcode = pcntl_wexitstatus($status); | |
if ($exitcode) { | |
exit(1); | |
} | |
} | |
return; | |
} | |
$l = count($arr); | |
for ($i = $proc_num; $i < $l; $i += PROCESSES_NUM) { | |
$func($arr[$i]); | |
} | |
exit(0); | |
} | |
parallelForeach([1, 2, 3, 4, 5, 6], function ($i) { | |
sleep(rand(0, 3)); | |
echo $i . "\n"; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment