gpt4 book ai didi

multithreading - 在perl中将线程队列对象作为对象变量传递

转载 作者:行者123 更新时间:2023-12-03 12:58:58 24 4
gpt4 key购买 nike

我正在写一个包,它接受诸如线程数,thread::Queue对象之类的输入。
创建包对象后,我将基于输入参数创建线程,并在每个线程中使输入队列出队,并且每个线程执行一个简单的unix命令,例如对服务器执行ping操作(为保持简单而进行了更改)。
下面是代码:

my $failed_q = Thread::Queue -> new();
my $success_q = Thread::Queue -> new();
my $process_q = Thread::Queue -> new();

package WorkerThreads;


sub new {
my $class = shift;
my $self = {
_ThreadCount => shift,
_FidQueue => shift,
_SuccessQueue => shift,
_FailedQueue => shift,
};
bless $self, $class;
return $self;
}

sub WorkerProcess
{
my ($self)=@_;

while ( my $fid = $self->{_FidQueue} -> dequeue() )
{
chomp ( $fid );
print threads -> self() -> tid(). ": pinging $fid\n";
my $result = `/bin/ping -c 1 $fid`;
if ( $? ) { $self->{_FailedQueue} -> enqueue ( $fid ) }
else { $self->{_SuccessQueue} -> enqueue ( $fid ) ; }
sleep 1;
}
print threads -> self() -> tid(). ":\n";
}


sub CreateThreads
{
my ($self)=@_;
my $Num_of_threads=$self->{_ThreadCount};

for ( 1..$Num_of_threads )
{
threads -> create ( \&WorkerProcess );
}

}

sub StartThreads
{
my ($self)=@_;

foreach my $thr ( threads -> list() )
{
$thr -> join();
}
}

sub PrintResult
{
my ($self)=@_;


while ( my $fid = $self->{_FailedQueue} -> dequeue_nb() )
{
print "$fid failed to ping\n";
}

#collate results. ('synchronise' operation)

while ( my $fid = $self->{_SuccessQueue} -> dequeue_nb() )
{
print "$fid Ping Succeeded\n";
}

}
sub ProcessRequest
{
my ($self)=@_;

$self->CreateThreads(@_);
$self->StartThreads(@_);
$self->PrintResult(@_);

}

package main;

#insert tasks into thread queue.
open ( my $input_fh, "<", "server_list" ) or die $!;
$process_q->enqueue( <$input_fh> );
close ( $input_fh );


my $Workers;

$Workers=WorkerThreads->new(
10,
$process_q,
$success_q,
$failed_q
);

$Workers->ProcessRequest();

我在尝试使队列未定义的while循环中出队时遇到错误。所以我有这样的疑问,就像我们可以将线程队列对象作为参数传递给包一样。
Thread 1 terminated abnormally: Can't call method "dequeue" on an undefined value at .

最佳答案

您正在将函数传递到threads->create中,而没有它们在其中处理哪个对象的任何上下文。这样的事情应该工作

threads->create( sub { $self->WorkerProcess } );

关于multithreading - 在perl中将线程队列对象作为对象变量传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55502275/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com