use*_*240 1 perl multithreading
我写了一个代码,我需要让它多线程.Evething工作,但每个循环重复4次:
use LWP::UserAgent;
use HTTP::Cookies;
use threads;
use threads::shared;
$| = 1;
$threads = 4;
my @groups :shared = loadf('groups.txt');
my @thread_list = ();
$thread_list[$_] = threads->create(\&thread) for 0 .. $threads - 1;
$_->join for @thread_list;
thread();
sub thread
{
my $url = 'http://www.site.ru/';
my $response = $web->post($url, Content =>
['st.redirect' => ''
]);
foreach $i (@groups)
{
my $response = $web->get($i);
if(!($response->header('Location')))
{
---------;
}
else
{
----------;
}
}
}
sub loadf {
open (F, "<".$_[0]) or erroropen($_[0]);
chomp(my @data = <F>);
close F;
return @data;
}
Run Code Online (Sandbox Code Playgroud)
groups.txt:
http://www.odnoklassniki.ru/group/47357692739634
http://www.odnoklassniki.ru/group/56099517562922
Run Code Online (Sandbox Code Playgroud)
我明白我需要使用threads :: shared; 但我无法理解如何使用它.
你的帖子没有太多的上下文来解释代码部分; 请更清楚地解释您的情景.
问题是你永远不会删除@groups,因此所有线程都会完成所有工作@groups.
这是一个解决方案.
use threads;
use Thread::Queue 3.01 qw( );
my $NUM_WORKERS = 4;
sub worker {
my ($url) = @_;
... download the page ...
}
my $q = Thread::Queue->new();
for (1..$NUM_WORKERS) {
async {
while (my $url = $q->dequeue()) {
worker($url);
}
};
}
$q->enqueue($_) for loadf('groups.txt');
$q->end();
$_->join() for threads->list;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
195 次 |
| 最近记录: |