Created
November 15, 2023 14:39
-
-
Save henricavalcante/cd6fa6964a6e58c97696e7bc12a75dfe to your computer and use it in GitHub Desktop.
PHP Async Example
This file contains 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 | |
$counter = 1; | |
function aJob(bool $async, int $pid) { | |
sleep(1); | |
global $counter; | |
echo "Async:" . ($async ? "true" : "false"); | |
echo " Pid:" . $pid; | |
echo " Count:" . $counter++ . "\n"; | |
return true; | |
} | |
$processes = []; | |
function anAsyncJob() { | |
$pid = pcntl_fork(); | |
if ($pid == -1) { | |
die('Process could not be forked'); | |
} | |
elseif ($pid == 0) { | |
aJob(true, getmypid()); | |
posix_kill(getmypid(), SIGKILL); | |
} | |
else { | |
$processes[] = $pid; | |
} | |
} | |
aJob(false, getmypid()); | |
aJob(false, getmypid()); | |
anAsyncJob(); | |
anAsyncJob(); | |
anAsyncJob(); | |
anAsyncJob(); | |
aJob(false, getmypid()); | |
foreach ($processes as $pid) { | |
pcntl_waitpid($pid, $status); | |
$status = pcntl_wexitstatus($status); | |
} | |
aJob(false, getmypid()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment