Skip to content

Instantly share code, notes, and snippets.

@sawantuday
Last active January 13, 2017 14:08
Show Gist options
  • Save sawantuday/76799779db91e88ef2dae844d59fec4d to your computer and use it in GitHub Desktop.
Save sawantuday/76799779db91e88ef2dae844d59fec4d to your computer and use it in GitHub Desktop.
A simple wrapper around PHP shm_* functions with semaphores. Any data structure that supports serialisation can be stored in shared memory and accessed across two or more processes.
<?php
class SharedMemory {
private $shmID;
private $semaphoreID;
public function __construct($token, $memSize=10000){
$this->shmID = shm_attach($token, $memSize);
$this->semaphoreID = sem_get($token);
if($this->shmID === false){
error_log("Failed to create shared memory segment");
}
}
public function __destruct(){
if($this->shmID) shm_detach($this->shmID);
// sem_release($this->semaphoreID);
}
public function getVar($key){
sem_acquire($this->semaphoreID);
$var = shm_has_var($this->shmID, $key) ? shm_get_var($this->shmID, $key) : false;
sem_release($this->semaphoreID);
return $var;
}
public function putVar($key, $val){
sem_acquire($this->semaphoreID);
$success = shm_put_var($this->shmID, $key, $val);
sem_release($this->semaphoreID);
return $success;
}
public function delVar($key){
sem_acquire($this->semaphoreID);
$success = shm_has_var($this->shmID, $key) && shm_remove_var($this->shmID, $key);
sem_release($this->semaphoreID);
return $success;
}
public function delSegment(){
sem_acquire($this->semaphoreID);
// shm_detach($this->shmID); // not required
$success = shm_remove($this->shmID);
sem_release($this->semaphoreID);
sem_remove($this->semaphoreID);
$this->shmID = null;
$this->semaphoreID = null;
return $success;
}
}
// $memory = new SharedMemory($token=1001);
// $memory->putVar(1, 1000);
// echo $memory->getVar(1);
// $memory->delVar(1);
// $memory->delSegment();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment