你能把$ self放入Perl中的Thread :: Queue吗?

时间:2013-06-27 14:14:21

标签: multithreading perl oop concurrency

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

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";
}

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

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