in reply to Doing two things at once, fork question.

With threads:

#! perl -slw use strict; use threads; use threads::shared; my @output :shared; my $pid :shared; my $t = async { $pid = open CMD, qq[ perl -le"\$|++; print ~~localtime while sleep 1" |] or die $!; while( <CMD> ) { chomp; lock @output; push @output, $_; } close CMD; }; sleep 10; ## do other stuff for my $out ( do{ lock @output; @output } ) { if( $out =~ m[6] ) { print $out; } } kill 9, $pid; $t->join;

Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.
"Too many [] have been sedated by an oppressive environment of political correctness and risk aversion."

Replies are listed 'Best First'.
Re^2: Doing two things at once, fork question.
by mhearse (Chaplain) on Mar 07, 2008 at 22:08 UTC
    Thanks for the example. One question. I've read the threads perldoc. async expects an anonymous subroutine. All of my code is in a module. Is there anyway I can call async with a method? I'm not sure what the syntax would be...
      Is there anyway I can call async with a method? I'm not sure what the syntax would be...

      Yes. (Update: Corrected method syntax)

      # normal sub - no parameters. my $thread = async \&subname; # sub with args my $thread = async \&subname, $arg1, $arg2; # method - no parameters. my $thread = async \&pClass::method, $obj; # method with args my $thread = async \&Classname::method, $obj, $arg1, $arg2;

      And note that async is just a functional alias for

      my $thread = threads->create( \&sub, $arg1, $arg2 ); my $thread = threads->new( \&Classname::method, $obj, $arg1, $arg2 );

      But note. Calling objects (object methods) across threads probably won't work in most cases.


      Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
      "Science is about questioning the status quo. Questioning authority".
      In the absence of evidence, opinion is indistinguishable from prejudice.

        How I would use a method:

        my $thread= async( sub { $obj->method( ... ) } );

        If one has some aversion to that technique for some reason, it is likely better to use the following hack rather some of those suggested in the above node:

        my $thread= async( $obj->can("method"), $obj, ... );

        - tye