Maybe the problem arises when trying to cycle through all keys of the hash at the exact same time its contents are being updated:

That makes a certain amount of sense in the version above with the sleeps removed. It's quite easy to see how (without locking) that the hash iterator could be corrupted. But that does not explain the earlier versions where you have sleeps that effectively orchestrate serialisation of the writing and reading of the hash.

Yes, you should be using locking. But for locking to be the fix for the original (with sleeps) version of the code, it would mean that iterating a 2 key hash would have to take longer than not just one timeslice (in order for the other thread to have a need to lock), but longer than 1 second. And that's just silly.

A quick test shows that Perl can iterate a two-key shared hash 10 million times in just over 4 seconds:

use threads; use threads::shared; use Time::HiRes qw[ time ]; my $h:shared = ( 1..4 ); print time; for ( 1..1e7 ) { 1 while each %h; } print time; 1227886927.80338 1227886932.10025

Even on a multicore box and with Data::Dumper in the mix, there's no way that the sleeping version of the code you posted could be concurrently modifying and iterating that hash.


Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.
"Too many [] have been sedated by an oppressive environment of political correctness and risk aversion."

In reply to Re^19: does threads (still) memleak? by BrowserUk
in thread does threads (still) memleak? by faxm0dem

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.