我有以下Perl代码::
#!/usr/bin/perl
use threads;
use Thread::Queue;
use DateTime;
$| = 1; my $numthreads = 20;
$min = 1;
$max = 100;
my $fetch_q = Thread::Queue->new();
our $total = 0;
sub fetch {
while ( my $target = $fetch_q->dequeue() ) {
print $total++ . " ";
}
}
my @workers = map { threads->create( \&fetch ) } 1 .. $numthreads;
$fetch_q->enqueue( $min .. $max );
$fetch_q->end();
foreach my $thr (@workers) {$thr->join();}
代码创建20个线程,然后递增变量$total
。
当前输出类似于:
0 0 0 0 0 1 0 0 1 1 2 0 0 1 0 2 0 3 0 1 0 2 1 0 2 1 0 0 3 0
但是所需的输出是:
1 2 3 4 5 6 7 8 9 10 .... 30
有没有办法让Perl增加变量?该命令无关紧要(即如果它是1 2 4 5 3则罚款。)
答案 0 :(得分:5)
use threads::shared;
my $total :shared = 0;
lock $total;
print ++$total . " ";