在Perl中使用多个线程时,如何减少内存消耗? [英] How do I reduce memory consumption when using many threads in Perl?
本文介绍了在Perl中使用多个线程时,如何减少内存消耗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想创建70多个线程,其中每个线程都以不同的值开头.
i want to create over 70 threads where every thread begins with a different value.
这是我的代码,目的是更清楚
here is my code in order to be more clear
use strict;
use warnings;
use threads;
use LWP::UserAgent;
my @char = (("A".."Z"),("a".."z"));
my @threads;
my $ua = LWP::UserAgent->new;
push @threads , threads->create(\&Chara);
sub Chara {
foreach my $a (@char){
foreach my $b (@char){
foreach my $c (@char){
foreach my $d (@char){
foreach my $e (@char){
my @req = ("http://localhost/login.php",['log' => "root" , 'pwd' => "A$e$d$c$b$a"]);
my $res = $ua->post(@req);
print "Trying A$e$d$c$b$a\n";
if ($res->as_string() =~ /302/ && $res->as_strint() =~ m/admin/i){
print "A$e$d$c$b$a\n";
exit;
}}}}}}};;
我用不同的值重复了70多次,并在脚本结尾处放了
and i repeated that over 70 times with different values and in the end of the script i put
$_->join foreach @threads;
但是当我运行脚本时,它会占用大量内存
but when i run the script it consumes a lot of memory
任何建议.
不好意思.
推荐答案
在导入线程之前使用fork,例如:
Use forks before you import threads, like:
use forks;
use threads;
或者您可以像以下代码一样限制线程:
or you can limit your threads like the following code:
#!perl
use strict;
use warnings;
use diagnostics;
use Data::Dumper;
use threads;
my @IPS;
for my $item (1..100) {
push @IPS, $item;
}
my @Threads;
for (1..5) {
last if !@IPS;
my $IP =shift(@IPS);
push @Threads, async{ Connect($IP) };
}
while (@Threads) {
my $thread = shift(@Threads);
my $response = $thread->join;
print Dumper($response);
if (@IPS) {
my $IP =shift(@IPS);
push @Threads, async{ Connect($IP) };
}
}
sub Connect {
my $ip = shift;
sleep(1);
my $r=int(rand(10));
return "test$r";
}
我希望有帮助!
这篇关于在Perl中使用多个线程时,如何减少内存消耗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文