PHP DevCenter

oreilly.comSafari Books Online.Conferences.

We've expanded our LAMP news coverage and improved our search! Search for all things LAMP across O'Reilly!

Search
Search Tips

advertisement

Listen Print Discuss Subscribe to PHP Subscribe to Newsletters

Using Shared Memory from PHP
Pages: 1, 2

Using Shared Memory and Semaphores

When learning something new, any practical developer wants to start using this technology in practice, even writing a simple "Hello World!" program. It's normal, so I'd like to describe the basic information you need to know before you can create that simple test code.



Shared memory is the fastest form of IPC, but it requires synchronization between storing and fetching data. You must remember that when designing your IPC. What then is the algorithm of using shared memory? In simple terms, it is:

  • Gain access to the shared memory using a semaphore.
  • Write data into the shared memory object.
  • When finished writing, notify other programs using a semaphore.

Synchronizing with the semaphore is necessary, because using a shared memory resource is almost the same as using a file resource, where locking and unlocking helps prevent corruption.

Now the question is, "How do I use semaphores?" It's actually pretty easy and understandable in example code. The only issue is that, as semaphores lock and unlock resources, they can block each other. Without a careful design, processes can compete with each other to obtain a semaphore, causing long delays while they wait for access. Then again, even in correctly designed code, there'll always be an upper performance limit in multiprocessor systems. For more detail, see any book dedicated to multiprocessing.

Here are a few examples that show how to use different IPC shared memory and semaphore functions. I've also included a longer example code listing at the end of this article. Here are the functions listed in the order of their appearance.

int sem_get (int key [, int max_acquire [, int perm]])

This function returns a semaphore's identifier. It will be positive on success and FALSE if an error occurs. Use the returned id to access the semaphore V with the given key.

If necessary, the semaphore can have access permissions as specified in the perm parameter. The default is 0666. The max_acquire parameter governs the number of processes that can access the semaphore simultaneously. This is 1 by default.

A second call to sem_get() for the same key will return another semaphore identifier, but both identifiers identify the same semaphore.

bool sem_acquire(int sem_identifier)

This function returns TRUE on success and FALSE on failure. It will block, if necessary, until it can acquire the requested semaphore. The process of trying to receive the semaphore will block endlessly if it exceeds the max_acquire setting.

All semaphores used in a process but not cleared explicitly will close automatically. This will generate a warning, though.

int shm_attach(int key [, int memsize [, int perm]])

This creates or opens a shared memory segment. shm_attach() returns the id to use to access the shared memory with the specified key. The memory will be mem_size bytes large. The default value is that of sysvshm.init_mem in the PHP configuration file (or 10,000 bytes, if that's not set). perm is an optional set of access permissions, 0666 by default.

The first call with a given key will create the segment. The second call with the same key will return another shared memory identifier, ignoring the other two parameters. Both identifiers permit the access to the same shared memory region.

mixed shm_get_var(int id, int variable_key)

This returns a variable, identified by variable_key from a shared memory region identified by id. The variable will remain in shared memory.

int shm_put_var(int shm_identifier, int variable_key, mixed variable)

This adds or updates a variable, identified by variable_key, in the shared memory segment identified by shm_identifier. It allows variables of all types.

bool sem_release(int sem_identifier)

This releases a semaphore if it's held by the current process. If not, it generates a warning. This function returns TRUE on success and FALSE if an error occurs.

After releasing a semaphore, call sem_acquire() again to reacquire it.

int shm_remove(int shm_identifier)

This deletes a shared memory segment, destroying all contained data.

bool sem_remove(int sem_identifier)

This deletes a semaphore identified by sem_identifier, if it was created with sem_get. It returns TRUE on success and FALSE if an error occurs. If there's no semaphore with the given id, it will generate a warning. The semaphore is not available after deletion.

Sample Shared Memory Code

With the descriptions out of the way, here's some sample code that uses semaphores and shared memory functions:

<?php
MEMSIZE = 512; //  size of shared memory to allocate
$SEMKEY = 1;   //  Semaphore key
$SHMKEY = 2;   //  Shared memory key

echo "Start.\n";

// Create a semaphore
$sem_id = sem_get($SEMKEY, 1);
if ($sem_id === false)
{
    echo "Failed to create semaphore";
    exit;
}
else
    echo "Created semaphore $sem_id.\n";

// Acquire the semaphore
if (! sem_acquire($sem_id))
{
    echo "Failed to acquire semaphore $sem_id.\n";
    sem_remove($sem_id);
    exit;
}
else
    echo "Success acquiring semaphore $sem_id.\n";

// Attach shared memory
$shm_id = shm_attach($SHMKEY, $MEMSIZE);
if ($shm_id === false)
{
    echo "Fail to attach shared memory.\n";
    sem_remove($sem_id);
    exit;
}
else
    echo "Success to attach shared memory : $shm_id.\n";

// Write variable 1
if (!shm_put_var($shm_id, 1, "Variable 1"))
{
    echo "Failed to put var 1 in shared memory $shm_id.\n";

    // Clean up nicely
    sem_remove($sem_id);
    shm_remove($shm_id);
    exit;
}
else
    echo "Wrote var1 to shared memory.\n";

// Write variable 2
if (!shm_put_var($shm_id, 2, "Variable 2"))
{
    echo "Failed to put var 2 on shared memory $shm_id.\n";

    // Clean up nicely
    sem_remove($sem_id);
    shm_remove ($shm_id);
    exit;
}
else
    echo "Wrote var2 to shared memory.\n";

// Read variable 1
$var1 = shm_get_var($shm_id, 1);
if ($var1 === false)
{
    echo "Failed to retreive Var 1 from Shared memory $shm_id, " .
         "return value=$var1.\n";
}
else
    echo "Read var1=$var1.\n";

// Read variable 1
$var2 = shm_get_var ($shm_id, 2);
if ($var1 === false)
{
     echo "Failed to retrive Var 2 from Shared memory $shm_id, " .
          "return value=$var2.\n";
}
else
    echo "Read var2=$var2.\n";

// Release semaphore
if (!sem_release($sem_id))
    echo "Failed to release $sem_id semaphore.\n";
else
    echo "Semaphore $sem_id released.\n";

// Remove shared memory segment
if (shm_remove ($shm_id))
    echo "Shared memory successfully removed.\n";
else
    echo "Failed to remove $shm_id shared memory.\n";

// Remove semaphore
if (sem_remove($sem_id))
    echo "Semaphore removed successfully.\n";
else
    echo "Failed to remove $sem_id semaphore.\n";

echo "End.\n";

?>

Now here's some sample code for various shared memory operations:

<?php
// 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 the size of shared memory block
$shm_size = shmop_size($shm_id);
echo "SHM Block Size: ". $shm_size . " has been created.\n";

// 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";
}

// Read back the string
$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";

// 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);

?>

For more information about these or other functions, see the official PHP manual.

Alexander Prohorenko is a certified professional, who holds Sun Certified System Administrator and Sun Certified Java Programmer certifications.


Return to the PHP DevCenter.


Have a question about the theory or his examples? Ask Alexander here.
You must be logged in to the O'Reilly Network to post a talkback.
Post Comment
Full Threads Oldest First

Showing messages 1 through 1 of 1.

  • ipc with perl
    2004-05-17 06:42:56  cluedon [Reply | View]

    since this showed up on perl.com with a php title I thought I'd post some information about how to do this sort of thing with perl.

    check out http://search.cpan.org/~maurice/IPC-ShareLite-0.09/ShareLite.pm

    example code:


    $share = new IPC::ShareLite( -key=>1971,
    -create=>'yes',
    -destroy=>'no' ) or die $!;


    $share->lock();
    $share->store("This is going in shared memory");
    $share->unlock;


    $str = $share->fetch();








Tagged Articles

Post to del.icio.us

This article has been tagged:

php

Articles that share the tag php:

Understanding MVC in PHP (477 tags)

The PHP Scalability Myth (123 tags)

The Dynamic Duo of PEAR::DB and Smarty (53 tags)

PHP Form Handling (43 tags)

Very Dynamic Web Interfaces (39 tags)

View All

ipc

Articles that share the tag ipc:

Using Shared Memory from PHP (3 tags)

View All

programming

Articles that share the tag programming:

Rolling with Ruby on Rails (1374 tags)

Very Dynamic Web Interfaces (279 tags)

Ajax on Rails (231 tags)

Understanding MVC in PHP (202 tags)

A Simpler Ajax Path (186 tags)

View All

Sponsored Resources

  • Inside Lightroom
Advertisement

Sponsored by:

O'Reilly Media

©2009, O'Reilly Media, Inc.
(707) 827-7000 / (800) 998-9938
All trademarks and registered trademarks appearing on oreilly.com are the property of their respective owners.
About O'Reilly
Academic Solutions
Authors
Contacts
Customer Service
Jobs
Newsletters
O'Reilly Labs
Press Room
Privacy Policy
RSS Feeds
Terms of Service
User Groups
Writing for O'Reilly
Content Archive
Business Technology
Computer Technology
Google
Microsoft
Mobile
Network
Operating System
Digital Photography
Programming
Software
Web
Web Design
More O'Reilly Sites
O'Reilly Radar
Ignite
Tools of Change for Publishing
Digital Media
Inside iPhone
O'Reilly FYI
makezine.com
craftzine.com
hackszine.com
perl.com
xml.com

Partner Sites
InsideRIA
java.net
O'Reilly Insights on Forbes.com