user1065000
user1065000

Reputation: 85

Perl Fork Threads Capture Output

I want to Fork 5 Processes which will all Create 100 Threads each for a small function. The issue is that this function is generating many values which I want to capture in a hash. I am able to do with a single process and creating 100 threads, but I am not able to do with forking multiple threads. This I am doing in Perl and using threads CPAN module for the same.

Upvotes: 2

Views: 1696

Answers (1)

mob
mob

Reputation: 118595

One does not fork multiple threads, one forks processes. Each new process runs in its own memory space, and changing any variable values in one process does not affect those values in any other process. To do what you want, you will need some sort of interprocess communication.

One simple way to implement this is to have each child process write its output to a file and to have the parent process read that file when the children are done. You could even have all the children write to the same file, if you are mindful of the concurrency issues:

sub write_child_output_to_file {
   my ($msg, $file) = @_;
   open my $fh, '>>', $file;
   flock $fh, 2;
   seek $fh, 0, 2;
   print $fh $msg;
   close $fh;
}

The Forks::Super module has features that can handle these details for you:

use Forks::Super;
use Data::Dumper;
my %foo;
for my $i (1 .. 5) {
    fork {
        share => [ \%foo ],
        sub => {
            # the code that will run in each child process.
            # Updates to the variable  %foo  in the child will be
            # available to the parent when the child finishes
            ...
        }
    };
}
waitall;
print "Data produced in all the children: ",
    Data::Dumper::Dumper(\%foo);

Upvotes: 2

Related Questions