Question
Is it safe for multiple threads to retrieve and store simple individual values in a shared hash without lock()with a hash
Can you prove it or call strong power?
Background
I figured that in the worst case, unlocked hash manipulations could lead to segfaults.
However, I recently saw code that coordinates the workflows in a way that the author considers safe. This code only performs simple samples and stores:
- A shared hash is a simple, shared hash (not user defined, tie () d-constructor)
- Values are simple scalars, not links, not on their own.
- Each key / value pair is uniquely stored and modified by one and only one thread
- All key / value pairs can be selected by any thread.
- No thread goes through a common hash (no
each(), no keys()and values())
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';
}
source
share