PHP共享内存用法实例分析
发布时间:2020-12-12 21:20:00 所属栏目:PHP教程 来源:网络整理
导读:本篇章节讲解PHP共享内存用法。供大家参考研究具体如下: 共享内存主要用于进程间通信 php中的共享内存有两套扩展可以实现 1、shmop 编译时需要开启 --enable-shmop 参数 实例: 2、用 Semaphore 扩展中的 sem 类函数 (用起来更方便,类似 key-va
本篇章节讲解PHP共享内存用法。分享给大家供大家参考,具体如下: 共享内存主要用于进程间通信 php中的共享内存有两套扩展可以实现 1、shmop 编译时需要开启 --enable-shmop 参数实例: 2、用 Semaphore 扩展中的 sem 类函数 (用起来更方便,类似 key-value 格式)注意:这两种方式不通用的 一个用共享内存和信号量实现的消息队列 shmId = shmop_open($shmkey,$this->memSize);
$this->maxQSize = $this->memSize / $this->blockSize;
// 申請一个信号量
$this->semId = sem_get($shmkey,1);
sem_acquire($this->semId); // 申请进入临界区
$this->init();
}
private function init ()
{
if (file_exists($this->filePtr)) {
$contents = file_get_contents($this->filePtr);
$data = explode('|',$contents);
if (isset($data[0]) && isset($data[1])) {
$this->front = (int) $data[0];
$this->rear = (int) $data[1];
}
}
}
public function getLength ()
{
return (($this->rear - $this->front + $this->memSize) % ($this->memSize)) /
$this->blockSize;
}
public function enQueue ($value)
{
if ($this->ptrInc($this->rear) == $this->front) { // 队满
return false;
}
$data = $this->encode($value);
shmop_write($this->shmId,$data,$this->rear);
$this->rear = $this->ptrInc($this->rear);
return true;
}
public function deQueue ()
{
if ($this->front == $this->rear) { // 队空
return false;
}
$value = shmop_read($this->shmId,$this->front,$this->blockSize - 1);
$this->front = $this->ptrInc($this->front);
return $this->decode($value);
}
private function ptrInc ($ptr)
{
return ($ptr + $this->blockSize) % ($this->memSize);
}
private function encode ($value)
{
$data = serialize($value) . "__eof";
echo '';
echo strlen($data);
echo '';
echo $this->blockSize - 1;
echo '';
if (strlen($data) > $this->blockSize - 1) {
throw new Exception(strlen($data) . " is overload block size!");
}
return $data;
}
private function decode ($value)
{
$data = explode("__eof",$value);
return unserialize($data[0]);
}
public function __destruct ()
{
$data = $this->front . '|' . $this->rear;
file_put_contents($this->filePtr,$data);
sem_release($this->semId); // 出临界区,释放信号量
}
}
/*
* // 进队操作 $shmq = new ShmQueue(); $data = 'test data'; $shmq->enQueue($data);
* unset($shmq); // 出队操作 $shmq = new ShmQueue(); $data = $shmq->deQueue();
* unset($shmq);
*/
更多关于PHP相关内容感兴趣的读者可查看本站专题:《》、《》、《》及《》 希望本文所述对大家PHP程序设计有所帮助。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |