Question
Is it safe for multiple threads to fetch and store simple, individual values in a shared hash without lock()
ing the hash?
Can you prove it or cite strong authority?
Background
My belief was that at worst unlocked hash manipulations could lead to segfaults.
However, I've very recently seen code that coordinates worker threads' activity in such a manner, which the author believes to be safe. The code in question performs only simple fetches and stores:
- The shared hash is a plain, shared hash (not a user-defined, tie()d construct)
- The values are simple scalars, not references and not themselves shared
- Each key/value pair is uniquely stored and modified by one and only one thread
- All key/value pairs may be fetched by any thread
- No thread iterates through the shared hash (no
each()
, nokeys()
norvalues()
looping)
Code Excerpt
my %status : shared;
for my $id (1 .. $n) {
threads->create(\&thread_routine);
}
sub thread_routine {
my $me = threads->tid();
$status{ $me } = 'Getting ready';
... do something ...
$status{ $me } = 'Thinking';
... do something else ...
$status{ $me } = 'Looking around';
for my $tid (threads->list) {
next if $tid == $me;
if ($status{ $tid } eq "Thinking") { ... react ... }
...
}
$status{ $me } = 'All done';
}