0

我一直试图将 Perl Monks ( http://www.perlmonks.org/?node_id=735923 ) 的第一个答案扩展到线程模型,但无济于事。我不断遇到无法通过 coderef 的问题

在我的超类中,我将线程池定义为包变量,因此它可以在子类之间共享:

package Things::Generic;

my $Qwork = new Thread::Queue;
my $Qresults = new Thread::Queue;

my @pool = map { threads->create(\&worker, $Qwork, $Qresults) } 1..$MAX_THREADS;

sub worker {
    my $tid = threads->tid;
    my( $Qwork, $Qresults ) = @_;
    while( my $work = $Qwork->dequeue ) {
        my $result = $work->process_thing();
        $Qresults->enqueue( $result );
    }
    $Qresults->enqueue( undef ); ## Signal this thread is finished
}

sub enqueue {
   my $self = shift;
   $Qwork->enqueue($self);
}

sub new {
  #Blessing and stuff
}
.
.

现在为子类。保证他们有一个 process_thing() 方法。

package Things::SpecificN;
use base qw (Things::Generic);

sub new() {
 #instantiate
}

sub do_things {
  my $self = shift;

  #enqueue self into the shared worker pool so that "process_thing" is called
  $self->enqueue();
}

sub process_thing() {
   #Do some work here
   return RESULT;
}

#

Main
my @things;

push @things, Things::Specific1->new();
push @things, Things::Specific2->new();
.
.
push @things, Things::SpecificN->new();

#Asynchronously kick off "work"
foreach my $thing (@things) {
    $thing->do_things();
}

我的目标是将“工作”列表放在队列中。每个线程都会从队列中提取工作并执行它,不管它是什么。每个事物都有它自己独特的工作,但是完成工作的函数将被保证称为“process_thing”。我只想让线程池从队列中获取一个条目并执行“某事”。我想我正在描述类似于 Android AsyncTask 的功能。

我的 Perl 对 Thread::Queue::Any 来说不够高

4

1 回答 1

1

$Qwork->enqueue($self); instead of $self->enqueue();

于 2013-06-27T00:55:33.910 回答