Skip to content

Instantly share code, notes, and snippets.

@ravanscafi
Created November 30, 2016 16:39
Show Gist options
  • Save ravanscafi/9288fffd47df96f0bd2e105fabb3d4d1 to your computer and use it in GitHub Desktop.
Save ravanscafi/9288fffd47df96f0bd2e105fabb3d4d1 to your computer and use it in GitHub Desktop.
Proof of Concept: Max Parallel execution in PHP, awaiting for all children to return before exiting.
<?php
$maxChildren = 4;
$totalChildren = 20;
$pids = [];
echo "Max parallel children: {$maxChildren}\nTotal children: {$totalChildren}\n\n";
for ($i = 1; $i <= $totalChildren; $i++) {
if (count($pids) >= $maxChildren) {
$pid = pcntl_wait($status);
unset($pids[$pid]);
}
echo "Giving Birth to Child $i\n";
if (($pid = pcntl_fork()) < 0) {
die('Could not give birth, perhaps we can adopt?');
} elseif ($pid) {
$pids[$pid] = $pid;
} else {
echo "I am alive! Child {$i}\n";
sleep(rand(1, 10));
echo "Time to go! Child {$i}\n";
exit;
}
}
echo "\n\nAll children has birthed, waiting for remaining children to live and pass away.\n\n";
while ($pids) {
$pid = pcntl_wait($status);
unset($pids[$pid]);
}
echo "\n\nThat was fun, cya :)\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment