Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Re: Inconsistent results with keys on thread shared hashes

by ikegami (Patriarch)
on Aug 03, 2022 at 06:11 UTC ( [id://11145912]=note: print w/replies, xml ) Need Help??


in reply to Inconsistent results with keys on thread shared hashes

Simpler:

for my $t (1..2) { threads->create(sub { while (1) { my $s = join '', sort keys %testOne; print "$t\t$s\n" if $s ne 'ABCDE'; } }); } sleep;

You are both reading and modifying the hash — specifically its iterator — in multiple threads. You need a lock.

Replies are listed 'Best First'.
Re^2: Inconsistent results with keys on thread shared hashes
by izomiac (Novice) on Aug 03, 2022 at 18:59 UTC
    Ok... I had no idea hash iterators were a thing... I'd always just assumed keys was a read-only function that used local variables to iterate through the hash keys, though that's probably overstating how much thought I've even put into how hashes work under the hood. Thank you, I've used the keys function so long I never would have thought I had an incomplete understanding of how it worked.
Re^2: Inconsistent results with keys on thread shared hashes
by Anonymous Monk on Aug 03, 2022 at 19:17 UTC

    A shared hash in list context (my @a = %testOne) counts as modifying its internal iterator, too? (@a size will get 10,4,12,18 or whatever). And neither such assignment nor keys built-in are "atomic" thread-wise then, and it's not a bug? Yes, using a lock helps. In scalar context it evaluates to 1, not to number of keys. Not documented anywhere, neither.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11145912]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others sharing their wisdom with the Monastery: (3)
As of 2024-04-16 04:33 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found