Created
February 13, 2023 05:04
-
-
Save ammardev/21f1a2a51dd1e003804b59c131f67d66 to your computer and use it in GitHub Desktop.
Multi Processing Using PHP
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
<?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