我正在使用threads
和threads::shared
模块编写perl脚本,其中父进程可以在子执行过程中检索子线程的结果。
例如。我需要在以下脚本
中的flag = 1时获取子线程的输出#!/usr/bin/perl
use strict;
use warnings;
use threads;
use threads::shared;
my $flag : shared = 0;
my $num : shared = 0;
my $thr = new threads(\&sub1);
my @res = $thr->join();
print "@res" if ($flag != 0);
sub sub1
{
for( $num=0;$num<1000;$num++)
{
print "$num\t";
}
print "\n";
$flag = 1;
sleep(5);
for( $num=50;$num<100;$num++)`enter code here`
{
print "$num\t";
}
print "\n";
}
答案 0 :(得分:0)
您希望在线程内外等待设置/取消设置标志。请参阅代码中的注释:
#!/usr/bin/perl
use strict;
use warnings;
use threads;
use threads::shared;
my $flag : shared = 0;
my $num : shared = 0;
my $thr = new threads(\&sub1);
# do some things here
#wait for thread to set the flag
while( $flag == 0) {}
print "Outside thread: num=$num\n";
#unset flag so thread can continue
$flag = 0;
# do some things here
#block until thread finishes
my @res = $thr->join();
print "Outside thread: num=$num\n";
print @res;
sub sub1
{
#do initial calculations in thread
for( $num=0;$num<1000;$num++)
{
print "$num\t";
}
print "\n";
#set flag to parent can read value
$flag = 1;
#wait for parent to unset the flag
while($flag==1) {}
#continue with rest of thread
for( $num=50;$num<100;$num++)
{
print "$num\t";
}
print "\n";
return "I'm done\n";
}