1.使用 pcntl 扩展
$childPids = [];
for ($i = 0; $i < $numProcesses; $i++) {
$pid = pcntl_fork();
if ($pid == -1) {
die('Fork failed');
} elseif ($pid == 0) {
exit(0);
} else {
$childPids[] = $pid;
}
}
foreach ($childPids as $pid) {
pcntl_waitpid($pid, $status);
}
2.使用进程池
$poolSize = 5;
$pool = [];
for ($i = 0; $i < $poolSize; $i++) {
$pid = pcntl_fork();
if ($pid == -1) {
die('Fork failed');
} elseif ($pid == 0) {
while (true) {
}
exit(0);
} else {
$pool[$pid] = true;
}
}
foreach ($tasks as $task) {
while (true) {
$pid = pcntl_waitpid(-1, $status, WNOHANG);
if ($pid > 0) {
$pool[$pid] = true;
}
foreach ($pool as $pid => $busy) {
if (!$busy) {
$pool[$pid] = false;
break;
}
}
}
}
while (count($pool) > 0) {
$pid = pcntl_waitpid(-1, $status);
unset($pool[$pid]);
}