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 ?


In reply to Re^3: Help on Understanding Locks in Multithreading by gone2015
in thread Help on Understanding Locks in Multithreading by koti688

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.