Why is this print 12 times?

I am studying Perl multithreading. My code is:

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);

I want to print the word test $howmanyonce in streams $threads. This code prints the test 12 times. Where is the problem?

+5
source share
3 answers

Then I think you want for (0..$threads-1)or for (1..$threads)rather thanfor (0..$threads)

:-)

+10
source

Can an alternative approach be proposed?

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;

Benefits:

  • More scalable
  • Works even if $ num_work_units / $ num_workers is not an integer.
  • It does not assume that all work units take the same amount of time to complete.

Conclusion:

1
5
2
8
9
10
7
3
4
6
+11
source
for( 0..$threads )

6 : 0,1,2,3,4,5

+3

All Articles