Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re^3: Help on Understanding Locks in Multithreading

by gone2015 (Deacon)
on Feb 25, 2009 at 13:04 UTC ( [id://746251] : note . print w/replies, xml ) Need Help??


in reply to Re^2: Help on Understanding Locks in Multithreading
in thread Help on Understanding Locks in Multithreading

What are you expecting, and what did you get which doesn't meet with your expectation ?

FWIW, one wrinkle with threads is that the return context for the thread is set at threads->new time, not on the context of $thr->join(). Your code:

$thr = threads->new(\&sub1, "THREAD1 :"); ... @ReturnData = $thr->join; ...
should be:
($thr) = threads->new(\&sub1, "THREAD1 :"); ... @ReturnData = $thr->join; ...
to provide the right context at the right time.

The fragment:

{ lock $foo; $foo=0; }
is reasonably plausible. You're locking $foo for just long enough to give it a new value -- so there is no possibility of some other thread attempting to read or change $foo while it's in any intermediate state -- provided they too lock $foo before doing anything with it. (The lock is dropped at the end of the block it is contained in.)

I note that $foo is not initialised to anything.

I note that you:

print " Final value :$foo\n";
without locking it. But that's probably OK, because $foo is only changed by the same thread.

I wonder: you're not expecting $foo to work as some kind of semaphore, are you ?