欢迎您访问365答案网,请分享给你的朋友!
生活常识 学习资料

php消息队列的介绍

时间:2023-07-19



说明

1、消息队列是存放在内存中的一个队列。

2、由于消息队列去数据是,只有一个进程能去到,所以不需要额外的锁或信号量。

实例

echo "parent progress pid:{$parentPid}n";$childList = array();// 创建消息队列,以及定义消息类型(类似于数据库中的库)$id = ftok(__FILE__,'m');$msgQueue = msg_get_queue($id);const MSG_TYPE = 1;// 生产者function producer(){    global $msgQueue;    $pid = posix_getpid();    $repeatNum = 5;    for ( $i = 1; $i <= $repeatNum; $i++) {        $str = "({$pid})progress create! {$i}";        msg_send($msgQueue,MSG_TYPE,$str);        $rand = rand(1,3);        sleep($rand);    }}// 消费者function consumer(){    global $msgQueue;    $pid = posix_getpid();    $repeatNum = 6;    for ( $i = 1; $i <= $repeatNum; $i++) {        $rel = msg_receive($msgQueue,MSG_TYPE,$msgType,1024,$message);        echo "{$message} | consumer({$pid}) destroy n";        $rand = rand(1,3);        sleep($rand);    }}function createProgress($callback){    $pid = pcntl_fork();    if ( $pid == -1) {        // 创建失败        exit("fork progress error!n");    } else if ($pid == 0) {        // 子进程执行程序        $pid = posix_getpid();        $callback();        exit("({$pid})child progress end!n");    }else{        // 父进程执行程序        return $pid;    }}// 3个写进程for ($i = 0; $i < 3; $i ++ ) {    $pid = createProgress('producer');    $childList[$pid] = 1;    echo "create producer child progress: {$pid} n";}// 2个写进程for ($i = 0; $i < 2; $i ++ ) {    $pid = createProgress('consumer');    $childList[$pid] = 1;    echo "create consumer child progress: {$pid} n";}// 等待所有子进程结束while(!empty($childList)){    $childPid = pcntl_wait($status);    if ($childPid > 0){        unset($childList[$childPid]);    }}echo "({$parentPid})main progress end!n";

以上就是php消息队列的介绍,希望对大家有所帮助。

Copyright © 2016-2020 www.365daan.com All Rights Reserved. 365答案网 版权所有 备案号:

部分内容来自互联网,版权归原作者所有,如有冒犯请联系我们,我们将在三个工作时内妥善处理。