After writing a solution using MCE::Shared, I wanted to come back and give IPC::Shareable a try including locking. Here it is.

use strict; use warnings; use IPC::Shareable; my ( $glue, $options ) = ( 'data', { create => 1, exclusive => 0, mode => 0644, destroy => 1, }); tie my @data, 'IPC::Shareable', $glue, $options; if ( ! defined ( my $pid = fork() ) ) { die "Cannot fork!: $!"; } elsif ( $pid == 0 ) { # Child my $item; sleep 1; for ( my $i = 1; $i <= 10; $i++ ) { ( tied @data )->shlock; $item = shift @data; ( tied @data )->shunlock; $item = '' if ( ! defined $item ); print "Child: $item\n"; } } else { # Parent for ( my $i = 1; $i <= 10; $i++ ) { ( tied @data )->shlock; push @data, $i; ( tied @data )->shunlock; print "Parent: @data\n"; } waitpid( $pid, 0 ); }

It produces the following output on FreeBSD, Linux, and Mac OS X.

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

Notice how the construction for the shared variable is done before spawning. Also, the parent waits for the spawned worker to exit. Other than locking (optional for this use-case due to sleep in worker), everything else is similar to the OP's code.

Regards, Mario.


In reply to Re: IPC:Shareable: Not an array reference by marioroy
in thread IPC:Shareable: Not an array reference by Bloehdian

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.