1

I want to get a hash with all elements from all children using Parallel::ForkManager.

use strict;

use Parallel::ForkManager;

my @arr2 = (a, b, c, d);

foreach ( @arr2 ) {

    $pid = $pm->start

    $hash{$_} = localtime;

    # STORE ABOVE ELEMENT TO EXIST HASH

    my $pid = $pm->start and next;
}

$pm->wait_all_children;

READ %hash

output

$hash{a} = 11:02
$hash{b} = 11:03
$hash{c} = 11:04
$hash{d} = 11:05

Is it possible to share elements of hash by run_on_exit callback? Or I must use an external file? Which module does it in the easiest way? I tried IPC::Shareable and DBM::Deep. They do not work on my script.

F. Grela
  • 61
  • 5
  • It will work for Parallel::ForkManager ?? – F. Grela Mar 24 '18 at 17:12
  • 1
    Parallel::ForkManager` provides for a child process to send data back to parent, explained in its docs. The downside is that it uses files for this. See [this post](https://stackoverflow.com/a/41891334/4653379) and [this post](https://stackoverflow.com/a/40434889/4653379) for examples. – zdim Mar 24 '18 at 19:15
  • I tried IPC::Shareable. Had erros `IPC::Shareable::SharedMem: shmget: File exists at /home/f/perl5/lib/perl5/IPC/Shareable.pm line 567.` In DBM::Deep I had errors `DBM::Deep: Cannot write to a deleted spot in DBM::Deep. at ./backtest.pl line 581` and others. I read about run_on_exit and this way don't looking easy in my case. – F. Grela Mar 24 '18 at 19:31
  • Show your code using DBM::Deep and IPC::Shareable – ysth Mar 25 '18 at 06:21

1 Answers1

0

Threads can share data easily:

#!/usr/bin/perl
use warnings;
use strict;

use threads;
use Thread::Queue;

my $q = 'Thread::Queue'->new;

my @workers = map 'threads'->create(sub {
    $q->enqueue([ 'threads'->tid, scalar localtime ]);
}), 1 .. 4;

$_->join for @workers;

my %hash;
while ($q->pending) {
    my $data = $q->dequeue;
    $hash{ $data->[0] } = $data->[1];
}

use Data::Dumper; print Dumper \%hash;
choroba
  • 231,213
  • 25
  • 204
  • 289
  • [*"The use of interpreter-based threads in perl is officially discouraged"*](https://perldoc.perl.org/threads.html) – Borodin Mar 24 '18 at 13:49
  • 3
    @Borodin: I understand that people at IRC are tired of answering the same questions again and again, but I still don't understand why their feeling is reflected in the official documentation. – choroba Mar 24 '18 at 13:53
  • 2
    For details see https://www.nntp.perl.org/group/perl.perl5.porters/2015/05/msg227743.html or http://www.perlmonks.org/?node_id=1107534 . – choroba Mar 24 '18 at 14:07
  • That's very interesting; thank you. – Borodin Mar 24 '18 at 14:51
  • I'm using ForkManager not threads. I wrote this in question. – F. Grela Mar 24 '18 at 16:55
  • @F.Grela: **choroba** is saying that it would be simpler to use threads instead. – Borodin Mar 24 '18 at 17:44
  • This is not the answer to my question. I asked for a module to store the hash. I still have not found a solution. – F. Grela Mar 24 '18 at 19:24