Posted by: Sukhon | June 10, 2009

Shared memory

Shared memory by shm_op is an easy to use set of functions that allows PHP to read, write, create and delete Unix shared memory segments. you can use them to share data between different PHP scripts or even with other processes running in your server.

The first thing people generally do is cache things within their web processes. But this means your cache is duplicated multiple times, once for each mod_perl/PHP/etc thread. This is a waste of memory and you’ll get low cache hit rates. If you’re using a multi-threaded language or a shared memory API (IPC::Shareable, etc), you can have a global cache for all threads, but it’s per-machine. It doesn’t scale to multiple machines. Once you have 20 webservers, those 20 independent caches start to look just as silly as when you had 20 threads with their own caches on a single box. (plus, shared memory is typically laden with limitations)

One annoying thing is that shm_op requires to allocate a memory block first though the system don’t know how much memory it needs to handle data. That’s why, this is apperant that shm_op either block some spaces which are not used or cannot save data if allocated size is less than data size.

Installation

You have to enable shm_op extension from php.ini file and restart apache server.

Sample Code

// Create 100 byte shared memory block with system id of 0xff3
$shm_id = shmop_open(0xff3, “c”, 0644, 100);
if (!
$shm_id) {
echo
“Couldn’t create shared memory segment\n”;
}

// Get shared memory block’s size
$shm_size = shmop_size($shm_id);
echo
“SHM Block Size: ” . $shm_size . “ has been created.\n”;

// Lets write a test string into shared memory
$shm_bytes_written = shmop_write($shm_id, “my shared memory block”, 0);
if (
$shm_bytes_written != strlen(“my shared memory block”)) {
echo
“Couldn’t write the entire length of data\n”;
}

// Now lets read the string back
$my_string = shmop_read($shm_id, 0, $shm_size);
if (!
$my_string) {
echo
“Couldn’t read from shared memory block\n”;
}
echo
“The data inside shared memory was: ” . $my_string . “\n”;

//Now lets delete the block and close the shared memory segment
if (!shmop_delete($shm_id)) {
echo
“Couldn’t mark shared memory block for deletion.”;
}
shmop_close($shm_id);


Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Categories

Follow

Get every new post delivered to your Inbox.