Created
June 29, 2018 15:03
-
-
Save zofe/ec0ca00d9fb331332451d54001f8982b to your computer and use it in GitHub Desktop.
parallelize php process helper
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 | |
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