如何在Perl中的对象之间共享公共线程池?

时间:2013-06-26 20:32:35

标签: multithreading perl oop thread-safety multiprocessing

我一直试图将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();
}

我的目标是列出" work"在队列上。每个线程都会从队列中拉出工作并执行它,无论它是什么。每件事都有自己独特的工作,但是保证工作的功能被称为" process_thing"。我只是希望线程池从队列中获取一个条目并执行"某些事情"。我想我正在描述类似于Android AsyncTask的功能。

My Perl对于Thread :: Queue :: Any

来说不够高

1 个答案:

答案 0 :(得分:1)

$Qwork->enqueue($self);代替$self->enqueue();