
illustrate
1. The message queue is a queue stored in memory.
2. Since only one process can access the data in the message queue, no additional locks or semaphores are needed.
Example
echo "parent progress pid:{$parentPid}n";$childList = array();
//Create a message queue and define message types (similar to libraries in databases)
$id = ftok(__FILE__,'m');
$msgQueue = msg_get_queue($id);
const MSG_TYPE = 1;
// producer 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);
}
}
//Consumer 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) {
//Creation failed exit("fork progress error!n");
} else if ($pid == 0) {
// Subprocess execution program $pid = posix_getpid();
$callback();
exit("({$pid})child progress end!n");
}else{
//The parent process executes the program return $pid;
}
}
// 3 writing processes for ($i = 0; $i < 3; $i ++ ) {
$pid = createProgress('producer');
$childList[$pid] = 1;
echo "create producer child progress: {$pid} n";
}
// 2 writing processes for ($i = 0; $i < 2; $i ++ ) {
$pid = createProgress('consumer');
$childList[$pid] = 1;
echo "create consumer child progress: {$pid} n";
}
// Wait for all child processes to end while(!empty($childList)){
$childPid = pcntl_wait($status);
if ($childPid > 0){
unset($childList[$childPid]);
}
}
echo "({$parentPid})main progress end!n";The above is an introduction to PHP message queue. I hope it will be helpful to everyone.