Home  >  Article  >  Backend Development  >  Code examples for sending data and getting data from php message queue

Code examples for sending data and getting data from php message queue

不言
不言forward
2018-11-24 15:21:462378browse

The content of this article is about the code examples of sending data and obtaining data through PHP message queue. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Test of sending data to message queue and getting data

 B -> c,d,e... 等进程。
 * 作为A来说,只需要生产任务,然后交给B 来处理。B 则会将任务分配给10个子进程来进行处理。
 * 
 */
//设定脚本永不超时
set_time_limit(0);
$ftok = ftok(__FILE__, 'a');
$msg_queue = msg_get_queue($ftok);
$pidarr = []; 
//产生子进程
$pid = pcntl_fork();
if ($pid) {
    //父进程模拟生成一个特大的数组。
    $arr = range(1,100000);
    //将任务放进队里,让多个子进程并行处理
    foreach ($arr as $val) {
        $status = msg_send($msg_queue,1, $val);
        usleep(1000);
    }   
    $pidarr[] = $pid;
    msg_remove_queue($msg_queue);
} else {
    //子进程收到任务后,fork10个子进程来处理任务。
    for ($i =0; $i<10; $i++) {
        $childpid = pcntl_fork();
        if ($childpid) {
            $pidarr[] = $childpid; //收集子进程processid
        } else {
            while (true) {
                msg_receive($msg_queue, 0, $msg_type, 1024, $message);
                if (!$message) exit(0);
                echo $message.PHP_EOL;
                usleep(1000);
            }   
        }   
    }   
}
//防止主进程先于子进程退出,形成僵尸进程
while (count($pidarr) > 0) {
    foreach ($pidarr as $key => $pid) {
        $status = pcntl_waitpid($pid, $status);
        if ($status == -1 || $status > 0) {
            unset($pidarr[$key]);
        }   
    }   
    sleep(1);
}

The above is the detailed content of Code examples for sending data and getting data from php message queue. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete