I'm trying to find out when to lock a shared variable or not.

For scalars, it seems obvious: only when you want to modify it. It seems that there is no problem with concurrent read access to the same scalar, right?

Then, if you have one write and multiple reads to a single scalar, it seems you do not need locking either. Each read either gets the value before the write, or the one after, but not something else. Correct?

So, it seems you only need locking when you may have multiple concurrent write operations.

But what about hashes? Is it also true?

Are all the read operations below safe without locking?

my %h : shared; $x = $h{foo}; # R1 safe? @x = keys(%h); # R2 safe? while (($k, $v) = each(%h)) { ... } # R3 safe?

Then, is it ok, like for scalars, to have multiple reads and only one write without locking? Here are the write operations I have in mind:

$h{foo} = "change the existing 'foo' entry"; # W1 aka modification $h{bar} = "add a 'bar' entry"; # W2 aka insertion delete($h{zoi}); # W3 aka deletion

For R1, I hope that locking is not needed: you either get the value before the modification/insertion/deletion or the one after. Could you please confirm?.

Will R2 work while the hash is being modified? Of course, by the time you use the keys, the hash could have changed but if you simply access the hash with R1, there should be no problem: you may miss some keys or access non existing entries.

For R3, will it work at all?

Thanks in advance for your wisdom...


In reply to 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.