Skip to content

Instantly share code, notes, and snippets.

@henricavalcante
Created November 15, 2023 14:39
Show Gist options
  • Save henricavalcante/cd6fa6964a6e58c97696e7bc12a75dfe to your computer and use it in GitHub Desktop.
Save henricavalcante/cd6fa6964a6e58c97696e7bc12a75dfe to your computer and use it in GitHub Desktop.
PHP Async Example
<?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