Skip to content

Instantly share code, notes, and snippets.

@benrogmans
Created March 9, 2015 09:48
Show Gist options
  • Save benrogmans/d6b3aa653d58dc946bff to your computer and use it in GitHub Desktop.
Save benrogmans/d6b3aa653d58dc946bff to your computer and use it in GitHub Desktop.
Asynchronous loop
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' => 'johndoe@gmail.com'
],
[
'id' => 2,
'name' => 'Sarah Joe'
'email' => 'sarahjoe@gmail.com'
]
];
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