Created
July 29, 2022 17:37
-
-
Save frankiejarrett/49361fd3af27d039d080b9cceb3adfdf to your computer and use it in GitHub Desktop.
Apply a user supplied function to every member of an array, in parallel
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 | |
/** | |
* 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