You always have to lock shared variable when you accessing it
Wrong. Perl internally locks the variable before reading from or writing to it, so you don't need to lock it to avoid a corrupted value.

As to the OP's questions: R1 is safe, while R2 behaves like R3: i.e. it iterates over the hash pushing individual values onto @x. In R3, if another thread is adding or deleting elements, or also iterating, then it will affect the result in the same way as if a single thread was doing it, e.g.

while (($k, $v) = each(%h)) { # stuff here which adds or deletes elements, # or uses each/keys/values }
W1,2,3 are all safe.

Of course in all the above, "safe" means "not corrupting perl's internal state"; perl's internal locking causes all the reads and writes to be serialised. You may of course still need to do locking at a higher level to ensure the safety of your own code's logic

Dave.


In reply to Re^2: threads::shared - when to lock a hash ? by dave_the_m
in thread threads::shared - when to lock a hash ? by Anonymous Monk

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.