【问题标题】:perl queue files opening with threadsperl 队列文件用线程打开
【发布时间】:2013-01-11 00:37:43
【问题描述】:

我有简单的多线程站点检查器。 我尝试在此目录中打开循环 txt 文件

my @files = glob( '*.txt' );

foreach my $file(@files){

   @sites=load_file($file);
   $total_count = scalar(@sites);

   for my $t (1..$threads) {
     push @threads, threads->create(\&check, $t);#check- main subroutine
     threads->create(\&stat)->join() if $t == $threads;#stat - realtime statistics(good/bads) sites
   }

   foreach my $t (@threads) {
     $t->join();
   }
}

但它仅适用于第一个文件和程序终止。 任何人都可以帮忙吗? 谢谢。

【问题讨论】:

  • use strict; use warnings了吗? @threads 在哪里声明?为什么不将它声明为 inside 外循环?另外,我看不到线程和@sites 之间的任何交互。你知道Thread::Queue吗?
  • 是的。因为它与问题无关。子程序检查使用@sites。
  • 如果您不知道您的程序为何无法运行,那么您就无法说出与该问题相关的内容。请发布您的整个代码。我在这个片段中根本看不到任何声明,我怀疑在其他地方对 @sites$threads@threads 的处理不当。

标签: multithreading perl


【解决方案1】:

如果您使用 Perl 进行线程化,有几件事要避免:

  • 过多分叉/创建新进程
  • 共享状态,或共享任何不可变或不同步的东西!

您的代码使用硬连线限制$threads。但是您传递并索引到一个全局 (*shudder*) 数组(忘记了第一个索引),因此某些站点可能会未经检查。此外,您为每组网站创建一组新线程,这似乎很浪费。

现在假设我们有一个 Thread::Queue。然后我们从创建几个线程开始:

#!/usr/bin/perl

use strict; use warnings; use threads; use Thread::Queue;
use constant THREADS => 5; # or whatever

my $queue = Thread::Queue->new();

my @threads = map threads->new(\&check, $queue),  1 .. THREADS;

我们的check 子例程将队列作为参数,从中获取站点:

sub check {
  my $q = shift;
  while (defined(my $site = $q->dequeue)) {
    ...; # check the site.
  }
}

然后(在启动线程之后),我们用站点填充队列:

for my $file (@files) {
   my @sites = load_file($file);
   $queue->enqueue( @sites ); # keep queue operations to minimum
   # maybe wait until there are less that n sites in the queue
}

文件完成后,我们将undef值入队;这会导致线程终止:

$queue->enqueue( (undef) x THREADS );
$_->join for @threads;

【讨论】:

    【解决方案2】:

    “站点检查器”当然是一个 I/O 绑定问题,而线程/分叉更适合解决 CPU 绑定问题。如果您使用异步方法,网络上的并行请求可以是单进程。这是一个非常简单的检查器,使用来自 CPAN 的 YADA 模块,默认情况下使用 4 个并行连接:

    #!/usr/bin/env perl
    use common::sense;
    
    use YADA;
    
    YADA->new->append(
        [qw[
            http://www.cpan.org/modules/by-category/02_Language_Extensions/
            http://www.cpan.org/modules/by-category/02_Perl_Core_Modules/
            http://www.cpan.org/modules/by-category/03_Development_Support/
            http://www.cpan.org/modules/by-category/27_Pragma/
            http://www.cpan.org/modules/by-category/28_Perl6/
            http://www.cpan.org/modules/by-category/99_Not_In_Modulelist/
        ]] => sub {
            say $_[0]->final_url;
            say ${$_[0]->header};
        },
    )->wait;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-11
      • 2012-08-05
      • 1970-01-01
      • 2021-06-07
      • 1970-01-01
      • 2011-01-28
      相关资源
      最近更新 更多