Skip to content

Instantly share code, notes, and snippets.

@apinstein
Last active December 14, 2015 03:39
Show Gist options
  • Save apinstein/5022677 to your computer and use it in GitHub Desktop.
Save apinstein/5022677 to your computer and use it in GitHub Desktop.
php concurrency with pcntl_fork
$concurrency = 5;
if ($concurrency > 1)
{
print("Starting {$concurrency} workers via pcntl_fork\n");
$childPids = array();
$isMain = true;
foreach (range(1, $concurrency) as $i) {
$pid = pcntl_fork();
if ($pid === -1) throw new Exception("Forking failed.");
if ($pid === 0)
{
// we are the child
$isMain = false;
print("New fork started [{$i}]...\n");
break;
}
else
{
// $pid is forked child pid
$childPids[] = $pid;
}
}
if ($isMain)
{
foreach ($childPids as $pid)
{
pcntl_waitpid($pid, $status);
}
print("All kids exited.\n");
exit(0);
}
}
// do per-child stuff here
@apinstein
Copy link
Author

this works great except for if you intend to keep n workers running; it doesn't have a facility to act as a supervisor process or detect signals, etc.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment