in reply to IPC:Shareable: Not an array reference
Hi Bloehdian,
Re: I want to share an array between two processes created by fork()
The following demonstration provides a cross platform solution. MCE::Shared supports Unix (e.g: AIX, Darwin, FreeBSD, Linux, NetBSD, OpenBSD, Solaris, and possibly others), Windows (ActiveState/Strawberry Perl), and Cygwin. Also supported is Perl included with git-shell for Windows.
use strict; use warnings; use MCE::Shared; tie my @data, 'MCE::Shared'; if ( ! defined ( my $pid = fork() ) ) { die "Cannot fork!: $!"; } elsif ( $pid == 0 ) { # Child my $item; sleep 1; for ( my $i = 1; $i <= 10; $i++ ) { $item = shift @data; $item = '' if ( ! defined $item ); print "Child: $item\n"; } } else { # Parent for ( my $i = 1; $i <= 10; $i++ ) { push @data, $i; print "Parent: @data\n"; } waitpid( $pid, 0 ); }
The snippet produces the following output.
Parent: 1 Parent: 1 2 Parent: 1 2 3 Parent: 1 2 3 4 Parent: 1 2 3 4 5 Parent: 1 2 3 4 5 6 Parent: 1 2 3 4 5 6 7 Parent: 1 2 3 4 5 6 7 8 Parent: 1 2 3 4 5 6 7 8 9 Parent: 1 2 3 4 5 6 7 8 9 10 Child: 1 Child: 2 Child: 3 Child: 4 Child: 5 Child: 6 Child: 7 Child: 8 Child: 9 Child: 10
Regards, Mario.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: IPC:Shareable: Not an array reference
by marioroy (Prior) on Oct 11, 2016 at 03:02 UTC | |
by Bloehdian (Beadle) on Oct 11, 2016 at 03:54 UTC | |
by marioroy (Prior) on Oct 11, 2016 at 06:52 UTC | |
by marioroy (Prior) on Nov 01, 2016 at 22:19 UTC | |
|
Re^2: IPC:Shareable: Not an array reference
by Marshall (Canon) on Oct 11, 2016 at 06:17 UTC | |
by marioroy (Prior) on Oct 11, 2016 at 07:15 UTC |