Last active
August 29, 2015 13:56
-
-
Save SteelPangolin/9009942 to your computer and use it in GitHub Desktop.
This file contains 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 | |
function master() | |
{ | |
$num_partitions = 10; | |
// not every system has this :( | |
//setproctitle("Parallel master: {$num_partitions} partitions"); | |
$workers = []; | |
for ($partition = 0; $partition < $num_partitions; ++$partition) { | |
$pid = pcntl_fork(); | |
if ($pid === -1) { | |
echo "Fork problems\n"; | |
} elseif ($pid) { | |
// still in the parent process | |
$workers[$pid] = "running"; | |
} else { | |
// now in a child process | |
worker($partition); | |
} | |
} | |
master_print_scoreboard($workers); | |
$worker_errors = count($workers) < $num_partitions; | |
for ($num_active_workers = count($workers); $num_active_workers > 0; --$num_active_workers) { | |
$status = 0; | |
$pid = pcntl_wait($status); | |
$returncode = pcntl_wexitstatus($status); | |
if ($returncode) { | |
$worker_errors = true; | |
} | |
$workers[$pid] = $returncode | |
? "exited with code {$returncode}" | |
: "finished normally"; | |
master_print_scoreboard($workers); | |
} | |
exit((int)$worker_errors); | |
} | |
function master_print_scoreboard($workers) { | |
echo "Master: worker statuses: "; | |
var_dump($workers); | |
echo "\n"; | |
} | |
function worker($partition) | |
{ | |
// not every system has this :( | |
//setproctitle("Parallel worker: partition {$partition}"); | |
try { | |
worker_do_work($partition); | |
exit(0); // success | |
} catch (Exception $e) { | |
echo "Worker {$partition} exception: {$e->getMessage()}\n"; | |
exit(1); // error | |
} | |
} | |
function worker_do_work($partition) | |
{ | |
echo "Worker {$partition} taking a nap\n"; | |
sleep(10 + rand(0, 5)); | |
if ($partition === 4) { | |
throw new Exception("Being difficult"); | |
} | |
echo "Worker {$partition} waking up\n"; | |
} | |
master(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment