0

我在尝试将 $self 放入线程队列时遇到问题。Perl 抱怨 CODE refs。是否可以将对象实例放入线程队列中?

generic.pm (Superclass)

package Things::Generic;

use Thread::Queue;
use threads;

our $work_queue = new Thread::Queue;
our $result_queue = new Thread::Queue;

my @worker_pool = map { threads->create (\&delegate_task, $work_queue, $result_queue) } 1 .. $MAX_THREADS;

sub delegate_task {
    my( $Qwork, $Qresults ) = @_;
    while( my $work = $Qwork->dequeue ) {
            #The item on the queue contains "self" taht was passed in, 
            #  so call it's do_work method

            $work->do_work();
            $Qresults->enqueue( "lol" );
    }

    $Qresults->enqueue( undef ); ## Signal this thread is finished
}

sub new {
    my $class = shift;

    my $self = {
            _options => shift,
    };

    bless $self, $class;
    return $self;
}
.
.
.
#other instance methods

#

object.pm (Subclass)
package Things::Specific;

use base qw ( Things::Generic )

sub new {
        my $class = shift;
        my $self = $class->SUPER::new(@_);

        return $self;
}

sub do_stuff {
     my $self = shift;
     $Things::Generic::work_queue->enqueue($self);
}

sub do_work {
     print "DOING WORK\n";
}
4

2 回答 2

2

它不是有问题的对象;它里面有一个代码参考。这不是没有道理的。为什么要尝试与代码引用共享对象?您应该在线程之间共享数据,而不是代码。

于 2013-06-28T00:27:54.787 回答
0

虽然我不确定这一点,但可能的根本原因不是您正在传递一个对象,而是有问题的对象在其中存储了一个匿名 coderef(回调、迭代器等)。您可能能够重构对象以消除这种情况或执行某种序列化,以允许它在另一个线程中重新创建 coderef。

于 2013-06-27T14:43:15.590 回答