Multithreading 在子线程执行期间检索子线程输出
我正在使用和模块编写一个perl脚本,其中父进程可以在子线程执行过程中检索子线程的结果 例如,在下面的脚本中,当flag=1时,我需要得到子线程的输出Multithreading 在子线程执行期间检索子线程输出,multithreading,perl,Multithreading,Perl,我正在使用和模块编写一个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-
#!/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";
}
您希望在线程内外等待设置/取消设置标志。请参见代码中的注释:
#!/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";
}