NAME
IPC::Shm - Easily store variables in SysV shared memory.
SYNOPSIS
use IPC::Shm;
our %variable : shm;
Then, just use it like any other variable.
EXPLANATION
The "shm" variable attribute confers two properties:
- 1. The variable will persist beyond the program's end.
- 2. All simultaneous processes will see the same value.
Scalars, hashes, and arrays are supported.
Storing references is legal; however, the target of the reference will itself be moved into its own anonymous shared memory segment with contents preserved.
Blessed references might work but are untested.
LEXICALS
Lexical variables are treated as anonymous, and are supported. They will only outlive the process if another shared variable contains a reference to it.
LOCKING
If you need the state of the variable to remain unchanged between two or more operations, the calling program should assert a lock thus:
my $obj = tied %variable;
$obj->writelock; # or readlock, if no changes will be made
$variable{foo} = "bar";
$variable{bar} = $variable{foo};
$obj->unlock; # don't forget
To summarize the locking behavior, reads are prohibited while a writelock is in effect (and only one writelock may be held), and writes are prohibited while one or more readlocks are in effect.
CACHING
To avoid excessive serialization and deserialization, the underlying IPC::Shm::Simple class provides a serial number that automatically increments during writes. Perl uses this to indicate when a change has been made by another process, and otherwise the in-process cached copy is trusted.
ATOMICITY
Perl will read and write the entire variable at once, whether it be a scalar, array, or hash. At the lowest level, a C implementation just sees the serialized string. Updates can be considered atomic as reads are locked out during writes, and vice versa, using a SysV semaphore array.
SEGMENTS AND SEMAPHORES
One SysV shared memory segment and one SysV semaphore array for locking are created for each Perl variable, named or anonymous.
Only one segment, containing %IPC::Shm::NAMEVARS, uses an IPCKEY. It is currently defaulted to 0xdeadbeef, and will likely change in the future. One possible path would be to relate the IPCKEY to the effective userid.
By default, segments are created with 4096 bytes and 0660 permissions. To change that, you'd need to change the default before the variables are created:
sub BEGIN {
IPC::Shm::Tied->Size( 8192 );
IPC::Shm::Tied->Mode( 0600 );
}
CURRENT STATUS
This is alpha code. There are no doubt many bugs.
In particular, the multiple simultaneous process use case has not been tested.
Also, the garbage collection is primitive, and there is not yet a safe way to remove named variables other than manually removing ALL IPC::Shm segments.
AUTHOR
Kevin Cody-Little <kcody@cpan.org>