Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Pushing data into an array in fork

Status
Not open for further replies.

user2base

Technical User
Oct 16, 2002
29
0
0
GB
Does someone know how to push data into an array as part of a fork process ??
I always get an empty array.
My code looks like this (I am using Parallel::ForkManager):

my $pid;
my $pm = new Parallel:ForkManager(5);

foreach my $element (@list){
$pid = $pm->start and next;
...
$result = ....
...
push @array, $result;
$pm->finish;
}

print for @array;
 
Since you are using fork, the data cannot be shared between processes in a regular array. What you need is something like IPC::Sharable. You'd use it something like:
[tt]
use IPC::Shareable;

# Created array in shared memmory
my %opts = (
create => 1,
mode => 0600,
destroy => 1
);
my $key = 'mkey';

tie @shared_array, 'IPC::Shareable', $key, { %opts } or die "Failed to tie \@shared_array\n";

my $pid;
my $pm = new Parallel:ForkManager(5);

foreach my $element (@list){
$pid = $pm->start and next;
...
$result = ....
...

(tied @shared_array)->shlock; # lock array for update

push @shared_array, $result;
(tied @shared_array)->shunlock; # unlock the array

$pm->finish;
}

$pm->wait_all_children;


print for @shared_array;
[/tt]

The using locks is important so seperate procs don't overwrite each others results. Also don't forget to wait_all_children. If the main proc dies before the children then the shared array will be yanked out form under the children causing errors.

Hope that helps.
 
if you're using Perl 5.8.0 there's a good sharing mechanism for sharing between forked "processes" - on Win32 anyway

Mike

Want to get great answers to your Tek-Tips questions? Have a look at faq219-2884

It's like this; even samurai have teddy bears, and even teddy bears get drunk.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top