Skip to content

Instantly share code, notes, and snippets.

@ammardev
Created February 13, 2023 05:04
Show Gist options
  • Save ammardev/21f1a2a51dd1e003804b59c131f67d66 to your computer and use it in GitHub Desktop.
Save ammardev/21f1a2a51dd1e003804b59c131f67d66 to your computer and use it in GitHub Desktop.
Multi Processing Using PHP
<?php
class ProcessManager
{
private array $processes = [];
public function run($callback): void
{
$pid = pcntl_fork();
if ($pid === -1) {
// Operation failed.. skip
return;
}
if ($pid === 0) {
$callback();
exit();
}
$this->processes[] = $pid;
}
public function wait(): void
{
while (count($this->processes) > 0) {
foreach($this->processes as $key => $pid) {
$res = pcntl_waitpid($pid, $status, WNOHANG);
if($res == -1 || $res > 0) {
unset($this->processes[$key]);
}
}
sleep(1);
}
}
}
###########################################################################
function slowOperation() {
sleep(5);
echo 'done' . PHP_EOL;
}
$processManager = new ProcessManager();
foreach (range(0, 9) as $i) {
$processManager->run(fn() => slowOperation());
}
$processManager->wait();
echo 'All operations done' . PHP_EOL;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment