歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux基礎 >> 關於Linux >> linux共享內存的實現的php內存隊列

linux共享內存的實現的php內存隊列

日期:2017/3/2 9:54:20   编辑:關於Linux

<?php
/**
* 使用共享內存的PHP循環內存隊列實現
* 支持多進程, 支持各種數據類型的存儲
* 注: 完成入隊或出隊操作,盡快使用unset(), 以釋放臨界區
* /
class SHMQueue
{
private $maxQSize = 0; // 隊列最大長度

private $front = 0; // 隊頭指針
private $rear = 0; // 隊尾指針

private $blockSize = 256; // 塊的大小(byte)
private $memSize = 25600; // 最大共享內存(byte)
private $shmId = 0;

private $filePtr = './shmq.ptr';

private $semId = 0;
public function __construct()
{
$shmkey = ftok(__FILE__, 't');

$this->shmId = shmop_open($shmkey, "c", 0644, $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";
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);
?>

Copyright © Linux教程網 All Rights Reserved