develooper Front page | perl.perl5.porters | Postings from October 1999

Re: perlthread.pod -- First draft of thread docs

Tuomas J. Lukka
October 24, 1999 07:10
Re: perlthread.pod -- First draft of thread docs
Message ID:
Maybe really emphasize the fact that unlike in other languages, you should

Also, I really think that only allowing locks like this is troublesome:
we should also allow C<unlock>


On Fri, 22 Oct 1999, Dan Sugalski wrote:
> =head2 Locking
> Perl code must never access a variable simultaneously in two or more
> threads. The only way to safely do this is to lock the variable you're
> accessing with the lock() function. lock() is advisory, in that it
> only blocks other locks rather than actual access to a
> variable. Locks are dynamically scoped, much like the way local works,
> and stay locked until the lock goes out of scope.
> For example:
>     my $foo;
>     {
>         lock $foo; # $foo is now locked
> 	bar(1);	   # $foo stays locked even inside bar
>     } # When execution gets here, the lock on $foo is released
> Failure to lock variables will at best give wrong answers, at worst
> cause perl to coredump.
> The single exception is locking subroutines. If a thread locks a
> subroutine, perl will prevent any other thread from entering it until
> the lock is released.
> Locking aggregates, such as hashes and arrays, is perfectly legal, and
> will block (and be blocked by) locks on those arrays and
> hashes. B<Locking an aggregate will not lock each member of the
> aggregate!> This is very important to remember. The reason is
> simple--the only safe way to do it would be to walk the hash or array
> and lock each member separately, which is terribly
> inefficient. (There's no way that locking one of the elements of an
> aggregate could check the lock status of the entire aggregate, as an
> individual scalar doesn't keep track of what aggregate it's in)
> lock() will also do one free dereference. This sequence:
>     {
>         my ($foo, $bar);
> 	$foo = \$bar;
> 	lock $foo;
>     }
> will actually get the lock in $bar. This is done so locks taken on
> objects (or, rather, object references, which is what you usually use)
> will be handled properly. It's arguably a bug that the dereference is
> unconditional, rather than just done on references to blessed
> things. Don't, therefore, count on the automatic dereference working
> on references to non-blessed things. Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About