sub get_data { use threads; use threads::shared; my %result:shared; my $cnt:shared = 10; my $page_counter = sub { my $nb = shift; while ($cnt > 0) { my $n = $cnt; print "Thread # $nb treats string number $n\n"; my $data = 'запрос к серверу'; my @tmp = @{$data}; foreach (my $i = 0; $i <= $#tmp; $i++) { # проблемное место, хочу писать в расшаренный хеш %result = (%result, $tmp[$i] -> {'id'} => shared_clone([$tmp[$i] -> {'name1'}, $tmp[$i] -> {'name2'}])); } $cnt--; } }; for my $t (1..10) { threads -> create($page_counter, $t); } foreach my $t (threads -> list) { if ($t -> tid && !threads::equal($t, threads -> self)) { $t -> join(); } } return \%result; } 

I want to collect data in a hash from several streams, I do not understand how this is done correctly. Mana read until it reaches. Sample code above.

UPD . Added shared_clone, the result satisfies me.

  • And what difficulties arise that does not work here? Although it would not hurt you to block the hash for the duration of the recording, and most importantly, by assigning %result = () create a completely new hash, it is very slow and I think it knocks the sharing. add one $result{ $tmp[$i] -> {'id'} } = [...] element. About locks.stackoverflow.com/questions/586880/… - Mike
  • And what else is not visible when the threads terminate because the cycle is infinite and there is no way out of it. - Mike
  • Flows are terminated by the counter. In the example did not reflect - lost, when ripped out too much, probably. There are no problems with this. About the fact that a new hash is being created - I always write with strict included and do not understand a bit about creating a new hash. Isn't that a hash assignment to yourself? I'll try to deal with locks. Could the principle of the action of lock be short? - Pivoter
  • You first expand the hash to the list, and then create a new hash from this list. Emm ... what does lock principle mean ... well, it blocks the hash and another thread at the same time trying to take the lock stops and waits until the first one finishes working with the hash. although adding a single value lok most likely to anything. if you need to read and modify or atomically perform a few changes, then it is definitely necessary - Mike
  • by the way, I would write it in the form $result{ $_->{id} } = [ $_->{name1}, $_->{name2} ] for @{$data}; - Mike

0