Storing Arbitrary Data in Shared Memory






Storing Arbitrary Data in Shared Memory

Problem

You want a chunk of data to be available to all web server processes through shared memory.

Solution

Use the pc_Shm class shown in Figure. For example, to store a string in shared memory, used the pc_Shm::save( ) method, which accepts a key/value pair:

<?php
$shm = new pc_Shm();
$secret_code = 'land shark';
$shm->save('mysecret', $secret_code);
?>

Another process can then access that data from shared memory with the pc_Shm::fetch( ) method:

<?php
$shm = new pc_Shm();
print $shm->fetch('mysecret');
?>

Discussion

Occasionally there are times when you want to cache a value or set of values in shared memory for rapid retrieval. If your web server is busy with disk I/O, it may make sense to leverage the shmop functions to achieve greater performance with storage and retrieval of information in that cache.

The pc_Shm class has two convenient methods, pc_Shm::fetch( ) and pc_Shm::save( ), which abstract away the need to set memory addresses or explictly open and close the shared memory segments.

It's important to remember that, unlike setting a key/value pair in a regular PHP array, the shmop functions need to allocate a specific amount of space that the data stored there is expected to consume. The pc_Shm class allocates 16k for each value by default. If data you need to store is larger than 16k, you need to increase the amount of space the shmop functions should reserve. For example:

<?php
$shm = new pc_Shm();
$shm->setSize(24576); // 24k
$shm->save('longstring', 'Lorem ipsum pri eu simul nominati...');
?>

See Also

Recipe 11.5 and Recipe 5.6; the Memcache section of the PHP online manual at http://www.php.net/memcache. Memcache is a very fast and efficient alternative to the shmop functions. More information about memcache can be found at http://www.danga.com/memcached/. Also, the PECL apc module (http://pecl.php.net/apc) offers functions for storing data in shared memory.



 Python   SQL   Java   php   Perl 
 game development   web development   internet   *nix   graphics   hardware 
 telecommunications   C++ 
 Flash   Active Directory   Windows