Skip to content

Instantly share code, notes, and snippets.

@zofe
Created June 29, 2018 15:03
Show Gist options
  • Save zofe/ec0ca00d9fb331332451d54001f8982b to your computer and use it in GitHub Desktop.
Save zofe/ec0ca00d9fb331332451d54001f8982b to your computer and use it in GitHub Desktop.
parallelize php process helper
<?php
function parallelize($func, $arr, $procs=4)
{
//to work with collections
//but you can also use chunk() n.f.
$chunks = $arr->chunk(ceil((count($arr) / $procs)));
$pid = -1;
$children = array();
foreach ($chunks as $items) {
$pid = pcntl_fork();
if ($pid === -1) {
die('could not fork');
} else if ($pid === 0) {
// We are the child process. Pass a chunk of items to process.
array_walk($items, $func);
exit(0);
} else {
// We are the parent.
$children[] = $pid;
}
}
// Wait for children to finish.
foreach ($children as $pid) {
// We are still the parent.
pcntl_waitpid($pid, $status);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment