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

Respect, I'm working on an app with detatched threads. I've got a variable shared in the following manner. use threads; use threads::shared; our $var : shared = (); This is being accessed by various threads. Would I need to do a lock($var) when I use the variable in my threads? Or does Perl automatically provide locks on shared variables? Any help would be appreciated
  • Comment on does an explicitly shared variable need locks?

Replies are listed 'Best First'.
Re: does an explicitly shared variable need locks?
by dave_the_m (Monsignor) on Mar 12, 2006 at 11:37 UTC
    perl does implicit locking of shared variables each time they are accessed, chiefly to avoid perl's internal data structures from getting corrupted. However, perl will not protect a variable across multiple accesses; for example, $i++ involves a read followed by a write. In between, another thread may have modified the variable. The following code was run on a 4 CPU machine:
    #!/usr/bin/perl -w use threads; use threads::shared; my $i : shared = 0; push @t, threads->new( sub { $i++ for 1..100_000 } ) for 1..4; $_->join for @t; print "i=$i\n"; $ perl588t /tmp/p i=139728

    Dave.

      Thanks Dave