518

说明

1、信号量:是系统提供的一种原子操作,一个信号数量,同时只有一个进程能操作。

一个过程获得一个信号,必须被过程释放。

2、共享内存:是系统在存储器中打开的一个公共存储器区域,任何一个过程都可以访问。

在同一时刻,可以有多个过程访问该区域,为了保证数据的一致性,需要对该存储器区域进行锁定或信号。

实例

echo"parentprogresspid:{$parentPid\n";
$childList=array();

//创建共享内存,创建信号量,定义共享key
$shm_id=ftok(__FILE__,'m');
$sem_id=ftok(__FILE__,'s');
$shareMemory=shm_attach($shm_id);
$signal=sem_get($sem_id);
constSHARE_KEY=1;
//生产者
functionproducer(){
global$shareMemory;
global$signal;
$pid=posix_getpid();
$repeatNum=5;
for($i=1;$i<=$repeatNum;$i++){
//获得信号量
sem_acquire($signal);

if(shm_has_var($shareMemory,SHARE_KEY)){
//有值,加一
$count=shm_get_var($shareMemory,SHARE_KEY);
$count++;
shm_put_var($shareMemory,SHARE_KEY,$count);
echo"({$pid)count:{$count\n";
else{
//无值,初始化
shm_put_var($shareMemory,SHARE_KEY,0);
echo"({$pid)count:0\n";

//用完释放
sem_release($signal);

$rand=rand(1,3);
sleep($rand);


functioncreateProgress($callback){
$pid=pcntl_fork();
if($pid==-1){
//创建失败
exit("forkprogresserror!\n");
elseif($pid==0){
//子进程执行程序
$pid=posix_getpid();
$callback();
exit("({$pid)childprogressend!\n");
else{
//父进程执行程序
return$pid;


//3个写进程
for($i=0;$i<3;$i++){
$pid=createProgress('producer');
$childList[$pid]=1;
echo"createproducerchildprogress:{$pid\n";

//等待所有子进程结束
while(!empty($childList)){
$childPid=pcntl_wait($status);
if($childPid>0){
unset($childList[$childPid]);


//释放共享内存与信号量
shm_remove($shareMemory);
sem_remove($signal);
echo"({$parentPid)mainprogressend!\n";

以上就是php信号量和共享内存的介绍,希望对大家有所帮助。更多php学习指路:php教程

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。