php消息队列的介绍
作者:互联网
2022-05-24

说明
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消息队列的介绍,希望对大家有所帮助。
相关标签:
php消息队列
相关推荐
专题
+ 收藏
+ 收藏
+ 收藏
+ 收藏
+ 收藏
+ 收藏
最新数据
相关文章
Laravel13 + Vue3 的免费可商用 PHP 管理后台 CatchAdmin V5.2.0 发布
04/13
Python的管道符(|)联合类型语法糖
04/12
python win32COM 对象介绍调用Word、WPS 与应用生态
04/12
【Shopee Games 年终盛典技术揭秘】用 CLIP + 大模型 为 2 亿用户生成专属动漫形象
04/12
Python空值判断避坑指南 + 图片定点缩放逻辑优化实战
04/12
VectorStoreRetriever 三种搜索类型
04/12
Scikit-learn 零基础,从安装到实战机器学习模型
04/12
一文助你了解Langchain
04/12
Fastapi中的 lifespan
04/12
LangChain1.0 实现 PDF 文档向量检索全流程
04/12
AI精选
