<?php
$key = ftok(__FILE__, 's');
// 同时最多只能有一个进程进入临界区
$sem_id = sem_get($key, 1);
echo "This is a room,can only stay one people!\n\r";
// 派生子进程
$pid = pcntl_fork();
if ($pid == -1) {
exit('fork failed!');
} else if ($pid > 0) {
$name = 'parent';
} else {
$name = 'child';
}
echo "{$name} want to enter the room \n";
sem_acquire($sem_id);
// 原子操作开始
echo "{$name} in the room , other people can't enter!\n";
sleep(3);
echo "{$name} leave the room\n";
// 原子操作结束
sem_release($sem_id);
if ($pid > 0) {
pcntl_waitpid($pid, $status);
sem_remove($sem_id);//移除信号量
}
?>
标签:none