Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this print 12 times?

Tags:

perl

I am learning Perl's multithreading. My code:

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 $howmany times in $threads threads. This code prints test 12 times. Where is the problem?

like image 426
kopaty4 Avatar asked Jun 03 '11 00:06

kopaty4


People also ask

Why is my list printing multiple times Python?

The value is being printed multiple times because you are using print inside the recursive function. You should return instead of printing inside the recursive function.

How do you print a Python list 10 times?

Example: count = 0; while count < 10: print("My name is Vidyut") count += 1 else: print(“String is printed ten times!”)

How do you print 3 times in Python?

To print a string multiple times: Use the multiplication operator to repeat the string N times. Use the print() function to print the result. The print() function will print the string repeated the specified number of times.

How do you print number n times?

Using the * operator to print a character n times in Python We can use the * operator to mention how many times we need to print this value.


2 Answers

May I suggest an alternate approach?

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;

Advantages:

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

Output:

1
5
2
8
9
10
7
3
4
6
like image 170
ikegami Avatar answered Nov 26 '22 22:11

ikegami


Then I think you want for (0..$threads-1) or for (1..$threads), not for (0..$threads)

:-)

like image 30
Nemo Avatar answered Nov 26 '22 22:11

Nemo