nothingmuch has asked for the wisdom of the Perl Monks concerning the following question:

I need to have a multithreaded (or thread safe) data structure management lib.

Write (exclusive) locking may occur on a part of the structure when modifications are needed. Due to a wide range of subroutines called within exclusive lock operations being recursive, possibly comming round the same parts of the structure, I want to know if calling lock() on the same thing, in one thread, will block or not, or at least if there's some defined behaviour. Neither perlfunc lock or perlthrtut had any information on this.

I suppose the most logical work around will be to maintain a nonshared hash of locked parts.

The scheme is a reference to a semaphore, within the lockable part. Shared locks are granted by locking to the reference, and upping the semaphore by one. The lock is then released, and upon cease of shared use, the semaphore is downed witout locking.

Exclusive locks are granted by locking on the reference, and waiting for the semaphore to hit zero. when the lock on the reference goes out of scope, the exclusive lock is tossed.

-nuffin
zz zZ Z Z #!perl

Edit by tye to fix typo noted in reply

Replies are listed 'Best First'.
Re: lock() - dynamic or lexical?
by Elian (Parson) on Feb 14, 2003 at 20:38 UTC
    Lock is dynamic. It's aquired when the lock call is made, and held until the end of the scope. Like local, locks don't go missing when you make a sub or method call.

    Perl's locks are recursive, unless things have really changed, so it's safe for one thread to get the same lock several times, in which case the lock will be held until the last lock goes out of scope.

Correction: lock() - dynamic or lexical?
by nothingmuch (Priest) on Feb 14, 2003 at 20:25 UTC
    For some reason (i don't remember wether this is normal or not) i can't edit the post... I have a typo - "will lock or not". I ment "will block or not".

    -nuffin
    zz zZ Z Z #!perl