515

说明

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

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

实例

echo"parentprogresspid:{$parentPid\n";$childList=array();
//创建消息队列,以及定义消息类型(类似于数据库中的库)
$id=ftok(__FILE__,'m');
$msgQueue=msg_get_queue($id);
constMSG_TYPE=1;
//生产者
functionproducer(){
global$msgQueue;
$pid=posix_getpid();
$repeatNum=5;
for($i=1;$i<=$repeatNum;$i++){
$str="({$pid)progresscreate!{$i";
msg_send($msgQueue,MSG_TYPE,$str);
$rand=rand(1,3);
sleep($rand);


//消费者
functionconsumer(){
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);


functioncreateProgress($callback){
$pid=pcntl_fork();
if($pid==-1){
//创建失败
exit("forkprogresserror!\n");
elseif($pid==0){
//子进程执行程序
$pid=posix_getpid();
$callback();
exit("({$pid)childprogressend!\n");
else{
//父进程执行程序
return$pid;


//3个写进程
for($i=0;$i<3;$i++){
$pid=createProgress('producer');
$childList[$pid]=1;
echo"createproducerchildprogress:{$pid\n";

//2个写进程
for($i=0;$i<2;$i++){
$pid=createProgress('consumer');
$childList[$pid]=1;
echo"createconsumerchildprogress:{$pid\n";

//等待所有子进程结束
while(!empty($childList)){
$childPid=pcntl_wait($status);
if($childPid>0){
unset($childList[$childPid]);


echo"({$parentPid)mainprogressend!\n";
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。