0

aが等しくinfoなるまでバックグラウンドで実行されるように、これを書き直すにはどうすればよいですか?$awresult

#!/usr/bin/env perl
use 5.12.0;
use warnings;
use Term::ReadLine;

my $term = Term::ReadLine->new( 'something' );
$term->ornaments( 0 );

sub info { 
    # in the real script this runs some computations instead of the sleep
    # and returns some information.
    my ( $time ) = @_;
    sleep $time;
    return $time * 2;
}

my $value_returned_by_info = info( 10 ); # run this in the background
my $aw;

$aw = $term->readline( 'User input: ' );
if ( $aw eq 'result' ) {
    # if info() is still running in the background:
    # wait until info() returns because "$value_returned_by_info" is needed.
    say $value_returned_by_info;
}
else {
    # if info() is still running in the background:
    # let info() in the background because "$value_returned_by_info" is not needed here.
    say $aw;
}

$aw = $term->readline( 'User input: ' );
if ( $aw eq 'result' ) {
    # if info() is still running in the background:
    # wait until info() returns because "$value_returned_by_info" is needed.
    say $value_returned_by_info;
}
else {
    # if info() is still running in the background:
    # let info() in the background because "$value_returned_by_info" is not needed here.
    say $aw;
}

$aw = $term->readline( 'User input: ' );
if ( $aw eq 'result' ) {
    # if info() is still running in the background:
    # wait until info() returns because "$value_returned_by_info" is needed.
    say $value_returned_by_info;
}
else {
    # if info() is still running in the background:
    # let info() in the background because "$value_returned_by_info" is not needed here.
    say $aw;
}

say "End";
4

2 に答える 2

0

info別のプロセスで実行できる場合は、そのまま使用できますfork。それ以外の場合は、スレッド化されたバージョンの perl を使用する必要があります。

使用例fork

sub start_info {
  my @params = @_;
  my $pipe;
  my $pid = open($pipe, "-|");

  if (!$pid) {
     # this code will run in a sub-process
     # compute $result from @params
     # and print result to STDOUT
     sleep(10);
     my $result = "p = $params[0] - pid $$";
     print $result;
     exit(0);
  };

  my $r;
  return sub {
    return $r if defined($r);
    $r = <$pipe>;  # read a single line
    waitpid $pid, 0;
    $r;
  };
}

sub prompt {
  print "Hit return: ";
  <STDIN>;
}

my $info1 = start_info(4);
prompt();
print "result = ", $info1->(), "\n";

my $info2 = start_info(30);
prompt();
print "result = ", $info2->(), "\n";
于 2012-11-18T22:21:17.820 に答える