PHP 提供兩組共享記憶體 API:shmop(需編譯參數 --enable-shmop)與 Semaphore 擴充套件中的 shm_* 函式。前者操作原始記憶體區塊,後者以鍵值對方式存取,開發體驗較佳。
$shm_key = ftok(__FILE__, 't');
// 開啟/建立共享記憶體:c=建立或開啟,0644=權限,1024=位元組大小
$shm_id = shmop_open($shm_key, "c", 0644, 1024);
// 寫入(偏移量需在範圍內)
$size = shmop_write($shm_id, 'songjiankang', 0);
echo "write into {$size}";
// 讀取
$data = shmop_read($shm_id, 0, 100);
var_dump($data);
// 標記刪除(無進程存取時系統自動回收)
shmop_delete($shm_id);
// 關閉連結
shmop_close($shm_id);
$key = ftok(__DIR__, 'a');
$shm_id = shm_attach($key, 1024, 0777);
if ($shm_id === false) die('Unable to create shared memory segment');
// 設值
shm_put_var($shm_id, 111, 'value');
// 取值
$value = shm_get_var($shm_id, 111);
var_dump($value);
// 刪除特定鍵
// shm_remove_var($shm_id, 111);
// 移除整個段
shm_remove($shm_id);
// 斷開
shm_detach($shm_id);
結合 shmop 與 sem 實現環狀佇列,支援多進程安全入隊/出隊。
class ShmQueue {
private $maxQSize = 0;
private $front = 0;
private $rear = 0;
private $blockSize = 256;
private $memSize = 25600;
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], $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();
$shmq->enQueue('test data');
unset($shmq); // 釋放鎖
// 出隊
$shmq = new ShmQueue();
$data = $shmq->deQueue();
unset($shmq);