php 多进程 消息队列,[PHP] 多进程通信-消息队列使用
向消息隊列發送數據和獲取數據的測試
$key=ftok(__file__,'a');
//獲取消息隊列
$queue=msg_get_queue($key,0666);
//發送消息
//msg_send($queue, 1, "hello, 1");
//接收消息,如果接收不到會阻塞
msg_receive($queue, 1, $message_type, 1024, $message1);
//移除消息
//msg_remove_queue($queue);
//var_dump($message1);
/**
* 這段代碼模擬了一個日常的任務。
* 第一個父進程產生了一個子進程。子進程又作為父進程,產生10個子進程。
* 可以簡化為a -> 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);
}
希望與廣大網友互動??
點此進行留言吧!
總結
以上是生活随笔為你收集整理的php 多进程 消息队列,[PHP] 多进程通信-消息队列使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 虚拟主机选择php版本,虚拟主机的php
- 下一篇: 血虚风燥的症状