Windows system >> Windowsの知識 >  >> Linuxシステムチュートリアル >> Linuxチュートリアル >> PHPメモリキューのPHP共有メモリ実装

PHPメモリキューのPHP共有メモリ実装

  

<?php /** * 共有メモリを使用したループメモリキューの実装*複数のプロセスをサポートし、さまざまなデータ型のストレージをサポートします*処置:エンキューまたはデキュー操作を完了し、できるだけ早くunset()を使用してクリティカル・セクションを解放してください。* /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;パブリック関数__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();}プライベート関数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];}}}パブリック関数getLength(){return(($ this-> rear - $ this-> front + $ this-> memSize)%($ this-) > memSize))/$ this-> blockSize;}パブリック関数enQueue($ value){if($ this-> ptrInc($ this-> rear)== $ this-> front){//チームフルリターンfalse;} $ data = $ this-> encode($ value); shmop_write($ this-> shmId、$ data、$ this-> rear); $ this-> rear = $ this- > ptrInc($ this-> rear); trueを返す;}パブリック関数deQueue(){if($ this-> front == $ this-> rear){//チーム無効リターンfalse;} $ value = shmop_read($ this-> shmId、$ this-> front、$ this-> blockSize-1); $ this-> front = $ this-> ptrInc($ this-> front); return $ this-> decode($ value);}プライベート関数ptrInc($ ptr){return($ ptr + $ this-> blockSize)%($ this-> memSize);}プライベート関数encode($ value) {$ data = serialize($ value)。" __ eof"; if(st) Rlen($ data)> $ this-> blockSize -1){新しい例外をスローする(strlen($ data)。"はオーバーロードブロックサイズです!");} return $ data;}プライベート関数デコード($ value) ){$ data = explode(" __ eof"、$ value);戻り値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 = 'テストデータ'; $ shmq-> enQueue($ data);設定解除($ shmq); //デキュー操作$ shmq = new SHMQueue(); $ data = $ shmq-> deQueue();設定解除($ shmq);?>


Copyright © Windowsの知識 All Rights Reserved