Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Apply a user supplied function to every member of an array, in parallel
<?php
/**
* Apply a user supplied function to every member of an array, in parallel.
*
* @param array $array
* @param callable $callback First arg is the value, second arg is the key.
* @param mixed $arg Will be passed as the third parameter to the callback.
* @param int $maxProcesses
* @return bool
*/
function array_walk_async(array $array, callable $callback, $arg = null, int $maxProcesses = 20): bool
{
if (! function_exists('pcntl_fork')) {
return array_walk($array, $callback, $arg);
}
$pids = [];
foreach ((array) $array as $key => $value) {
if (count($pids) >= $maxProcesses) {
$pid = pcntl_waitpid(-1, $status);
unset($pids[$pid]);
}
$pid = pcntl_fork();
if ($pid > 0) {
$pids[] = $pid;
}
if ($pid === 0) {
$callback($value, $key, $arg);
exit;
}
}
foreach ($pids as $pid) {
pcntl_waitpid($pid, $status);
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment