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?
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.
Example: count = 0; while count < 10: print("My name is Vidyut") count += 1 else: print(“String is printed ten times!”)
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.
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.
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:
Output:
1
5
2
8
9
10
7
3
4
6
Then I think you want for (0..$threads-1)
or for (1..$threads)
, not for (0..$threads)
:-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With