Unlocked, general security for hash operations in streaming perl

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';
}
+3
source share
3 answers

Here is the answer from the authorities. From perlthrtut at the end of “Shared and Unshared Data”

Note that a shared variable ensures that if two or more threads try to change it at the same time, the internal state of the variable does not become corrupt. However, there are no guarantees beyond this, as explained in the next section.

, , .

+1

, , . lock , . , .

, , - threads::shared , , , . Perl, , .

+2

, .

docs docs, , END, . , , ?

my %hash : shared;

map {
        async { map { $hash{$_}++; } (1 .. 30); }
} (1 .. 300);

map {$_->join} (threads->list);

print Dumper \%hash;

, , 300 . .

+1

Source: https://habr.com/ru/post/1758987/


All Articles