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

Brothers-

I have (what seems to be) a trivial problem with threads. I have an object, and I'd like for it to be able to cond_signal to alert any interested threads of interesting events. My idea was to have different hash values store the signals.

However, all my attempts to lock the values of a hash fail with the error: "lock can only be used on shared values". Here is an example:
use strict; use warnings; use threads; use threads::shared; # make the shared value my %hash : shared; # create the key I want $hash{testElem} = 0; # attempt to lock it lock $hash{testElem}; # which fails.
Any suggestions? As far as I know, this should be a valid operation.

Replies are listed 'Best First'.
Re: Locking hash values
by jettero (Monsignor) on Dec 18, 2006 at 18:06 UTC
    You can sorta get this to work like so:
    my $scalar : shared = 0; my %hash; $hash{key} = \$scalar; lock $hash{key};

    I'm not sure how reliable that is when you start new threads though. You're probably better off just sticking with a few shared scalars in my opinion. Perl's threading isn't one of it's strongest features. At least you're not stuck with IPC.

    -Paul

      Perhaps I'm doing something wrong, but that code fails out as well...perl's threading hurts me, this should be a simple thing to do. Not only that, it's mentioned in the POD as working.

        I think that should be

        lock ${$hash{key}};

        The idea is that $scalar is shared, and therefore lockable.