线程共享 perl [英] thread shared perl
本文介绍了线程共享 perl的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我写了一个代码,我需要使它成为多线程的.Evething 有效,但每个循环重复 4 次:
i wrote a code and i need to make it multithreaded. Evething works, but every loop repeats 4 times:
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;
}
groups.txt :
groups.txt :
http://www.odnoklassniki.ru/group/47357692739634
http://www.odnoklassniki.ru/group/56099517562922
我知道我需要使用threads::shared;但我无法理解如何使用它.
I understand that i need to use threads::shared; but i can't undestand how to use it.
您的帖子没有太多上下文来解释代码部分;请更清楚地解释您的场景.
Your post does not have much context to explain the code sections; please explain your scenario more clearly.
推荐答案
问题是你永远不会从 @groups
中删除,所以所有线程都在 @groups
中完成所有工作>.
The problem is that you never remove from @groups
, so all threads do all jobs in @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;
这篇关于线程共享 perl的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文