in reply to Re^3: threads::shared - when to lock a hash ?
in thread threads::shared - when to lock a hash ?

The ops never return junk; they will return values consistent with whatever thread did the most recent update. For example, this will never die:
use threads; use threads::shared; my $x : shared; for (0..9) { threads->new(sub { while (1) { $x = $_[0]; die unless $x =~ /^\d$/; } }, $_ ); } sleep;
There is one iterator per shared object, which is why I mentioned earlier that if other threads do each/keys/value too, it will affect the result

Dave.

Replies are listed 'Best First'.
Re^5: threads::shared - when to lock a hash ?
by ikegami (Patriarch) on Oct 17, 2011 at 06:57 UTC

    So each isn't thread safe. That brings us to keys. Is keys uninterruptible, or just the parts that would cause corruption?

    Update: No, keys isn't thread safe either.

    use strict; use warnings; use threads; use threads::shared; use feature qw( say ); use constant NUM_THREADS => 10; my %h :shared = map { $_ => 1 } 'a'..'z'; my $size = () = keys(%h); my $done :shared; my @threads; for (1..NUM_THREADS) { push @threads, async { while (!$done) { my $test_size = () = keys(%h); if ($test_size != $size) { warn("$test_size != $size\n"); return; } } }; } sleep(10); $done = 1; $_->join() for @threads;
    11 != 26 42 != 26 15 != 26 38 != 26 13 != 26 41 != 26 15 != 26 41 != 26 13 != 26 45 != 26
      Nice. Adding sort keys %h to the warning shows really ugly things like these:
      bccfkllnppqw aaaaaaaaaabbbbbbbcdddddddddeeffffffffffffggggghhhhhhhhhhhhhhiiiiiiiiii +ijjjjjjjjjjjjjjjkkkkkkkklllllllllmmmmmmmnnnnnnnnnnooooooopppppppqqrrr +rrrrrrrrrrrrrrrsstttuuuuuuuuuuuuuuuuuvvvvvwwwwwwwwwxxxxxxxxxxxxxxxxyy +yyyyyyzz acdegkqstvwyz aabcccdddeeefggghijkkklmnpqqqrrssstttuvvvwwxyyyzz
      And so on.