我正在学习Perl的多线程。我的代码:
use warnings;
use threads;
use threads::shared;
$howmany = 10;
$threads = 5;
$to = int($howmany / $threads);
for (0 .. $threads) {$trl[$_] = threads->create(\&main, $_);}
for (@trl) {$_->join;}
sub main {
for (1 .. $to) {
print "test\n";
}
}
exit(0);
我想在$howmany
个帖子中打印 test $threads
次。
此代码打印 test 12次。问题在哪里?
答案 0 :(得分:11)
我可以建议另一种方法吗?
use strict;
use warnings;
use threads ;#qw( async );
use Thread::Queue qw( );
my $num_workers = 5;
my $num_work_units = 10;
my $q = Thread::Queue->new();
# Create workers
my @workers;
for (1..$num_workers) {
push @workers, async {
while (defined(my $unit = $q->dequeue())) {
print("$unit\n");
}
};
}
# Create work
for (1..$num_work_units) {
$q->enqueue($_);
}
# Tell workers they are no longer needed.
$q->enqueue(undef) for @workers;
# Wait for workers to end
$_->join() for @workers;
优点:
输出:
1
5
2
8
9
10
7
3
4
6
答案 1 :(得分:10)
然后我想你想要for (0..$threads-1)
或for (1..$threads)
,而不是for (0..$threads)
: - )
答案 2 :(得分:3)
for( 0..$threads )
运行 6 次:0,1,2,3,4,5