Multithreading perl多线程perl与活动线程一起退出
我编写perl脚本是为了完成某项任务,但我需要对其进行多线程处理,但我得到以下结果: Perl已退出活动线程: 2运行和未连接 0已完成且未连接 0正在运行并已分离 代码如下:Multithreading perl多线程perl与活动线程一起退出,multithreading,perl,multidimensional-array,Multithreading,Perl,Multidimensional Array,我编写perl脚本是为了完成某项任务,但我需要对其进行多线程处理,但我得到以下结果: Perl已退出活动线程: 2运行和未连接 0已完成且未连接 0正在运行并已分离 代码如下: use Net::Ping; use threads; use Benchmark qw(:hireswallclock); use threads::shared; my $starttime = Benchmark->new; my $finishtime;
use Net::Ping;
use threads;
use Benchmark qw(:hireswallclock);
use threads::shared;
my $starttime = Benchmark->new;
my $finishtime;
my $timespent;
my $num_of_threads = 2;
my @threads = initThreads();
my $inFile = $ARGV[0] ;
open(IN , "<$inFile") or die "can not find $inFile" ;
my @output: shared = <IN>;
chomp (@output) ;
my $chunk_size = @output / 2;
print($chunk_size);
#############################
######## PROCEDURES ########
#############################
# Subroutine that intializes an array that will contain all our threads:
sub initThreads{
my @initThreads; # Our array
for(my $i=1; $i<=$num_of_threads; $i++){
push(@initThreads, $i);
}
return @initThreads;
}
sub doScript{
my $id = threads->tid();
print "//////////////////////////////////////////////////////////////////////////////////////////////Starting thread $id\n";
my ($start, $end, $output) = @_;
for my $i ($start .. $end) {
## some stuff done
sleep 1 if 0.2 > rand;
}
print "/////////////////////////////////////////////////////////////////////////////////////////////////////////////////Thread $id done!\n";
threads->exit();
}
########################
######## MAIN ########----------------------------------------------------------------
########################
for my $chunk(1 .. 2){
my $start = ($chunk - 1) * $chunk_size;
push @threads, threads->create(
\&doScript,
$start,
($start + $chunk_size - 1),
\@output,
);
print("finish");
}
# This tells the main program to keep running until all threads have finished.
foreach(@threads){
threads->join();
}
$finishtime = Benchmark->new;
$timespent = timediff($finishtime,$starttime);
print "\nDone!\nSpent ". timestr($timespent);
#print "\nProgram Done!\nPress Enter to exit\n";
$a = <>;
close (IN);
错误被解决了,但脚本似乎什么也不做,线程在没有做任何事情的情况下启动和终止
有人能帮我吗 您得到该错误的原因与tin上所说的完全相同-您的代码在线程关闭之前退出。这通常发生在提前触发退出或死亡时 特别是,我认为您的问题可能在于重用
@threads
和initThreads()
后者返回一个数字列表,而不是任何线程。然后,当您在执行创建时,再将几个线程推到列表的末尾
在我看来,这很像某种逻辑错误
但我认为主要的问题是:
foreach(@threads){
threads->join();
}
实际上,您并没有加入特定的线程。您可能想要的是:
至少,如果您没有使用[1,2]
手动填充@threads
,这要归功于my@threads=initThreads()代码>您的代码除了打印一堆斜杠外,什么都不做。你看到输出了吗?你是说你想得到你注释掉的代码的帮助吗?
foreach(@threads){
threads->join();
}
foreach my $thr ( @threads ) {
$thr -> join();
}