Created
November 30, 2016 16:39
-
-
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.
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 | |
$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