在Perl中,如何等待线程并行结束? [英] In Perl, how can I wait for threads to end in parallel?

查看:181
本文介绍了在Perl中,如何等待线程并行结束?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Perl脚本,它启动2个线程,每个处理器一个.我需要它等待一个线程结束,如果一个线程结束了,就会产生一个新线程.似乎join方法会阻塞程序的其余部分,因此第二个线程要等到第一个线程完成的所有工作都达到目的之后,才能结束.

I have a Perl script that launches 2 threads,one for each processor. I need it to wait for a thread to end, if one thread ends a new one is spawned. It seems that the join method blocks the rest of the program, therefore the second thread can't end until everything the first thread does is done which sort of defeats its purpose.

我尝试了is_joinable方法,但这似乎也没有.

I tried the is_joinable method but that doesn't seem to do it either.

这是我的一些代码:

use threads;
use threads::shared;

@file_list = @ARGV;      #Our file list
$nofiles = $#file_list + 1; #Real number of files 
$currfile = 1;     #Current number of file to process

my %MSG : shared;              #shared hash

$thr0 = threads->new(\&process, shift(@file_list));
$currfile++;
$thr1 = threads->new(\&process, shift(@file_list));
$currfile++;

while(1){
 if ($thr0->is_joinable()) {
  $thr0->join;
        #check if there are files left to process
  if($currfile <= $nofiles){ 
   $thr0 = threads->new(\&process, shift(@file_list));
   $currfile++;
  }
 }

 if ($thr1->is_joinable()) {
  $thr1->join;
        #check if there are files left to process
  if($currfile <= $nofiles){
   $thr1 = threads->new(\&process, shift(@file_list));
   $currfile++;
  }
 }
}

sub process{
       print "Opening $currfile of $nofiles\n";
       #do some stuff
       if(some condition){
               lock(%MSG);
               #write stuff to hash
       }
       print "Closing $currfile of $nofiles\n";
}

此输出为:

Opening 1 of 4
Opening 2 of 4
Closing 1 of 4
Opening 3 of 4
Closing 3 of 4
Opening 4 of 4
Closing 2 of 4
Closing 4 of 4

推荐答案

我认为您需要移动将列表中的下一个文件拉到线程本身中的代码.

I think you need to move the code that pulls the next file from the list into the threads themselves.

因此,每个线程不仅会处理一个文件,还会继续处理直到列表为空.

So every thread would not just process one file, but continue to process until the list is empty.

这样,您还可以节省创建新线程的时间.

This way, you also save on the overhead of creating new threads all the time.

然后,您的主线程将同时加入这两个线程.

Your main thread will then join both of them.

当然,这需要在列表上进行同步(以便它们不会提取相同的数据).或者,您可以将列表分成两部分(每个线程一个),但这可能会导致分布不佳.

Of course, this requires synchronization on the list (so that they do not pull the same data). Alternately, you could split the list into two (one for each thread), but that might result in an unlucky distribution.

(PS:没有Perl上帝,只是一个谦虚的和尚)

(PS: No Perl God, just a humble monk)

这篇关于在Perl中,如何等待线程并行结束?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆