【问题标题】:Keeping count with threads in perl在 perl 中使用线程计数
【发布时间】:2014-04-29 22:57:22
【问题描述】:

每当线程在 perl 中完成时,我都会尝试计数,并打印计数。但这不起作用。我不断得到“0”或“1”,我试图添加到计数中,然后在发出获取请求后立即打印计数。

use strict;
use threads;
use LWP::UserAgent;

our $MAX //= $ARGV[1];

my $list = $ARGV[0];
open my $handle, '<', $list;
chomp(my @array = <$handle>);
close $handle;
my $lines = `cat $list | wc -l`;
my $count = 0;

my @threads;
foreach $_ (@array) {
    push @threads, async{
        my @chars = ("a".."z");
        my $random = join '', map { @chars[rand @chars] } 1 .. 6;

        my $ua = LWP::UserAgent->new;
        my $url = $_ . '?session=' . $random;
        my $response = $ua->get($url);
        count++;
        print $count;
    };
    sleep 1 while threads->list( threads::running ) > $MAX;
}
$_->join for @threads;

【问题讨论】:

标签: multithreading perl count


【解决方案1】:

只是为了总结 @choroba 和我自己在 cmets 中的观点,不要没有答案就离开这个问题。

您需要包括:

use threads::shared;

在您的代码中,以及所有其他 use 元素。

并且表明变量$count是共享的:

my $count :shared = 0;

编辑根据池上的评论,如果你想修改它,你必须锁定变量,以避免并发问题。

{
    lock($count);
    $count++;
    print $count;
}

这应该足以共享变量$count

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-10
    • 2017-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-24
    相关资源
    最近更新 更多