IPC and counters

Simon Wistow simon at thegestalt.org
Wed Oct 15 00:08:43 BST 2008


On Tue, Oct 14, 2008 at 11:39:22PM +0100, Paul Makepeace said:
> Isn't this exactly what semaphores are for?
> 
> http://perldoc.perl.org/IPC/Semaphore.html
> (http://en.wikipedia.org/wiki/Semaphores)

Hah! The original subject of my post was "IPC and semaphores" but I 
changed it lest I do one of those "Ask an answer for the wrong solution 
instead of asking for a solution for the problem" questions.

I had a quick look at IPC::Semaphore but the docs seem pretty bad. 
Except that I've just noticed the section on semops which is probably 
what I want.

    Parent:

    my $n   = scalar(@children);
    my $id  = $message->id;
    my $sem = IPC::Semaphore->new(IPC_PRIVATE, 2, IPC_CREAT);
    $sem->setall(0, $n);
    foreach my $child (@children) {
        $child->send($message, $sem->id);
    }

    Child:

    my ($msg, $sem_id)  = get_message();
    my $sem = IPC::Semaphore->new($sem_id);
    $sem->op(0, 1, IPC_NOWAIT);
    if ($sem->getval(0)==1) {
        do_something($message);
    }
    # ... otherwise ignore it

    # If we're the last then clean up
    $sem->op(1,-1, IPC_NOWAIT);
    if ($sem->getval(1)==0) {
        $sem->remove;
    }

Cheers,

Simon


More information about the london.pm mailing list