
說明
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訊息隊列的介紹,希望對大家有幫助。