为什么要打印12次?

时间:2011-06-03 00:33:16

标签: perl

我正在学习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次。问题在哪里?

3 个答案:

答案 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;

优点:

  • 更具伸缩性
  • 即使$ num_work_units / $ num_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