Skip to content

Instantly share code, notes, and snippets.

@SteelPangolin
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SteelPangolin/9009942 to your computer and use it in GitHub Desktop.
Save SteelPangolin/9009942 to your computer and use it in GitHub Desktop.
<?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