php 多进程 消息队列,[PHP] 多进程通信-消息队列使用
向消息隊列發(fā)送數(shù)據(jù)和獲取數(shù)據(jù)的測試
$key=ftok(__file__,'a');
//獲取消息隊列
$queue=msg_get_queue($key,0666);
//發(fā)送消息
//msg_send($queue, 1, "hello, 1");
//接收消息,如果接收不到會阻塞
msg_receive($queue, 1, $message_type, 1024, $message1);
//移除消息
//msg_remove_queue($queue);
//var_dump($message1);
/**
* 這段代碼模擬了一個日常的任務(wù)。
* 第一個父進程產(chǎn)生了一個子進程。子進程又作為父進程,產(chǎn)生10個子進程。
* 可以簡化為a -> b -> c,d,e... 等進程。
* 作為a來說,只需要生產(chǎn)任務(wù),然后交給b 來處理。b 則會將任務(wù)分配給10個子進程來進行處理。
*
*/
//設(shè)定腳本永不超時
set_time_limit(0);
$ftok = ftok(__file__, 'a');
$msg_queue = msg_get_queue($ftok);
$pidarr = [];
//產(chǎn)生子進程
$pid = pcntl_fork();
if ($pid) {
//父進程模擬生成一個特大的數(shù)組。
$arr = range(1,100000);
//將任務(wù)放進隊里,讓多個子進程并行處理
foreach ($arr as $val) {
$status = msg_send($msg_queue,1, $val);
usleep(1000);
}
$pidarr[] = $pid;
msg_remove_queue($msg_queue);
} else {
//子進程收到任務(wù)后,fork10個子進程來處理任務(wù)。
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);
}
希望與廣大網(wǎng)友互動??
點此進行留言吧!
總結(jié)
以上是生活随笔為你收集整理的php 多进程 消息队列,[PHP] 多进程通信-消息队列使用的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 虚拟主机选择php版本,虚拟主机的php
- 下一篇: PHP在WPS中的应用,PHP+Lara