Created
March 9, 2015 09:48
-
-
Save benrogmans/d6b3aa653d58dc946bff to your computer and use it in GitHub Desktop.
Asynchronous loop
This file contains hidden or 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
function async_loop($array, $function) { | |
foreach($array as $key => $item) { | |
$pid = pcntl_fork(); | |
if ($pid) { | |
$childs[] = $pid; | |
} else { | |
$function($key, $item); | |
exit(); | |
} | |
} | |
while(count($childs) > 0) { | |
foreach($childs as $key => $pid) { | |
$res = pcntl_waitpid($pid, $status, WNOHANG); | |
// If the process has already exited | |
if($res == -1 || $res > 0) | |
unset($childs[$key]); | |
} | |
} | |
} | |
// Use like this: | |
$subscribers = [ | |
[ | |
'id' => 1, | |
'name' => 'John Doe' | |
'email' => '[email protected]' | |
], | |
[ | |
'id' => 2, | |
'name' => 'Sarah Joe' | |
'email' => '[email protected]' | |
] | |
]; | |
async_loop($subscribers, function($key, $subscriber){ | |
$email = new Send_email($subscriber); | |
$email->send(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment