PHP 8.5.0 Alpha 4 available for testing

Voting

: max(one, eight)?
(Example: nine)

The Note You're Voting On

cyrus at hirvi dot com
2 years ago
Here is an APCu alternative (instead of shared memory) function of fork_process by `kenneth at fellowrock dot com` https://www.php.net/manual/en/function.pcntl-fork.php#115855

<?php
// usage
$namespace = 'some_namespace';
$processes = [
function () {
sleep(1);
return
'Hello';
},
function () {
sleep(1);
return
' world!';
},
];
$callback = function ($result) {
echo
$result[0] . $result[1];
};
threadize($namespace, $processes, $callback);

function
threadize(string $namespace, $processes, callable $callback)
{
apcu_store($namespace . '_monitor', 0, 86400 * 3);
for (
$i = 0; $i < count($processes); $i++) {
$pid = pcntl_fork();
if (!
$pid) {
if (
$i == 1) {
usleep(100000);
}
apcu_store($namespace . '_process_result_' . $i, $processes[$i](), 86400 * 3);
apcu_inc($namespace . '_monitor');
exit(
0);
}
}
while (
pcntl_waitpid(0, $status) != -1) {
if (
apcu_fetch($namespace . '_monitor') === count($processes)) {
$result = [];
for (
$i = 0; $i < count($processes); $i++) {
$result[$i] = apcu_fetch($namespace . '_process_result_' . $i);
apcu_delete($namespace . '_process_result_' . $i);
}
$callback($result);
apcu_delete($namespace . '_monitor');
}
}
}
?>

<< Back to user notes page

To Top