Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/perl/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Multithreading 如何在Perl中的对象之间共享公共线程池?_Multithreading_Perl_Oop_Thread Safety_Multiprocessing - Fatal编程技术网

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

Multithreading 如何在Perl中的对象之间共享公共线程池?,multithreading,perl,oop,thread-safety,multiprocessing,Multithreading,Perl,Oop,Thread Safety,Multiprocessing,我一直在尝试将Perl Monks()的第一个答案扩展到线程模型,但没有成功。我总是因为无法通过coderef而遇到问题 在我的超类中,我将threadpool定义为一个包变量,以便它可以在子类之间共享: package Things::Generic; my $Qwork = new Thread::Queue; my $Qresults = new Thread::Queue; my @pool = map { threads->create(\&worker, $Qwor

我一直在尝试将Perl Monks()的第一个答案扩展到线程模型,但没有成功。我总是因为无法通过coderef而遇到问题

在我的超类中,我将threadpool定义为一个包变量,以便它可以在子类之间共享:

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()方法

#

我的目标是在队列中列出“工作”。每个线程都将从队列中提取工作并执行它,不管它是什么。每件事都有它自己独特的工作,但是完成这项工作的功能将被保证称为“过程”。我只想让线程池从队列中抓取一个条目并执行“something”。我想我描述的功能类似于Android AsyncTask


我的Perl不够高,不适合Thread::Queue::Any

$Qwork->enqueue($self)而不是
$self->enqueue()

“仍然”?你从来没有提到过对代码引用的任何抱怨。事实上,您的代码在代码引用方面没有任何问题,因为它使用的是任何代码引用。看看
Storable
-
freeze
saw
是在队列中移动对象的极好方法
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();
}