我正在使用Perl库HTTP::Async,如下所示:
use strict;
use warnings;
use HTTP::Async;
use Time::HiRes;
...
my $async = HTTP::Async->new( ... );
my $request = HTTP::Request->new( GET => $url );
my $start = [Time::HiRes::gettimeofday()];
my $id = $async->add($request);
my $response = undef;
while (!$response) {
$response = $async->wait_for_next_response(1);
last if Time::HiRes::tv_interval($start) > TIME_OUT;
}
...
当循环超时和脚本结束时while
我遇到以下错误消息:
HTTP::Async object destroyed but still in use at script.pl line 0
HTTP::Async INTERNAL ERROR: 'id_opts' not empty at script.pl line 0
我有哪些选择?如果仍在使用中,但不再需要,如何"清理"HTTP::异步对象?
我建议您remove
不完整的请求,但该模块不提供任何接口来执行此操作。
选项 1:添加移除功能。
将以下内容添加到脚本中:
BEGIN {
require HTTP::Async;
package HTTP::Async;
if (!defined(&remove)) {
*remove = sub {
my ($self, $id) = @_;
my $hashref = $self->{in_progress}{$id}
or return undef;
my $s = $hashref->{handle};
$self->_io_select->remove($s);
delete $self->{fileno_to_id}{ $s->fileno };
delete $self->{in_progress}{$id};
delete $self->{id_opts}{$id};
return $hashref->{request};
};
}
if (!defined(&remove_all)) {
*remove_all = sub {
my ($self) = @_;
return map $self->remove($_), keys %{ $self->{in_progress} };
};
}
}
您应该联系作者,看看他是否可以添加此功能。 $id
是 add
返回的值。
选项 2:将析构函数发出的所有警告静音。
如果您可以不为所有请求提供服务,那么静音警告也没有什么坏处。您可以按如下方式执行此操作:
use Sub::ScopeFinalizer qw( scope_finalizer );
my $async = ...;
my $anchor = scope_finalizer {
local $SIG{__WARN__} = sub { };
$async = undef;
};
...
请注意,这将静音在对象销毁期间发生的所有警告,所以我不太喜欢这样。
更通用的解决方案,对HTTP::Async进行子类化并不难。我使用它来中止所有挂起的请求:
package HTTP::Async::WithFlush;
use strict;
use warnings;
use base 'HTTP::Async';
use Time::HiRes qw(time);
sub _flush_to_send {
my $self = shift;
for my $request (@{ $self->{to_send} }) {
delete $self->{id_opts}->{$request->[1]};
}
$self->{to_send} = [];
}
sub _flush_in_progress {
my $self = shift;
# cause all transfers to time out
for my $id (keys %{ $self->{in_progress} }) {
$self->{in_progress}->{$id}->{finish_by} = time - 1;
}
$self->_process_in_progress;
}
sub _flush_to_return {
my $self = shift;
while($self->_next_response(-1)) { }
}
sub flush_pending_requests {
my $self = shift;
$self->_flush_to_send;
$self->_flush_in_progress;
$self->_flush_to_return;
return;
}
1;
使用模块内部比使用@ikegami代码更容易(也许)。