Last active
December 14, 2015 03:39
-
-
Save apinstein/5022677 to your computer and use it in GitHub Desktop.
php concurrency with pcntl_fork
This file contains hidden or 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
$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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.