gpt4 book ai didi

multithreading - 用数组请求多线程

转载 作者:行者123 更新时间:2023-12-05 04:23:31 25 4
gpt4 key购买 nike

此脚本读取 url 文件以执行多线程 HTTP 请求。

如何使用带有 url 的数组来发出多线程请求?

我的阵列将有类似的东西:

@array = ("https://example.com/xsd","https://example.com/xys","https://example.com/des","https://example.com/hduei");

我需要去掉通过url读取文件的功能,但是我做不到。

#!/usr/bin/perl
use strict;
use warnings;
use threads;
use threads::shared;

use Fcntl qw( LOCK_EX );
use IO::Handle qw( );
use LWP::UserAgent qw( );
use Thread::Queue 3.01 qw( );

use constant NUM_WORKERS => 20;

my $output_lock :shared;
my $output_fh;
sub write_to_output_file {
lock($output_lock);
print($output_fh @_);
$output_fh->flush();
}

sub worker {
my ($ua, $url) = @_;
my $response = $ua->get($url);
write_to_output_file("$url\n")
if $response->success
&& $response->content =~ /Exist/;
}

{
$output_fh = \*STDOUT; # Or open a file.

my $q = Thread::Queue->new();
for (1..NUM_WORKERS) {
async {
my $ua = LWP::UserAgent->new( timeout => 15 );
while (my $job = $q->dequeue()) {
worker($ua, $job);
}
};
}

while (<>) {
chomp;
$q->enqueue($_);
}

$q->end();
$_->join() for threads->list();
}

最佳答案

您显示的这部分代码从命令行参数读取文件名,然后读取这些文件中的所有行。然后它遍历这些行。

   while (<>) { # <--- here
chomp;
$q->enqueue($_);
}

您可以用一个数组替换它,这当然需要一个 for 循环。确保删除 chomp,因为不需要删除换行符。

   foreach (@urls) {
$q->enqueue($_);
}

关于multithreading - 用数组请求多线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73690415/

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