I’m making some tests using threads in Perl 5.10.1 but I’m having some problems. First of all I have Debian GNU/Linux squeeze/sid with 2.6.32-5-amd64 (64 bits).
This is my script
#!/usr/bin/perl -w
use strict;
use warnings;
use threads;
sub threadProcess{
my ($number, $counter) = @_;
print "Enter thread #" . $number . "\n";
while($counter < 10){
print "Thread #" . $number . ": " . $counter . "\n";
$counter++;
}
print "Exit thread #" . $number . "\n";
}
sub main{
my $counter = 0;
my $thr1 = threads->create(\&threadProcess, 1, $counter);
my $thr2 = threads->create(\&threadProcess, 2, $counter);
my $res1 = $thr1->join();
my $res2 = $thr2->join();
print "Bye...\n";
}
main(@ARGV);
And this is the output:
Enter thread #1
Thread #1: 0
Thread #1: 1
Thread #1: 2
Thread #1: 3
Thread #1: 4
Thread #1: 5
Thread #1: 6
Thread #1: 7
Thread #1: 8
Thread #1: 9
Exit thread #1
Enter thread #2
Thread #2: 0
Thread #2: 1
Thread #2: 2
Thread #2: 3
Thread #2: 4
Thread #2: 5
Thread #2: 6
Thread #2: 7
Thread #2: 8
Thread #2: 9
Exit thread #2
Bye...
What may be the problem? Thanks in advance!
Nothing, except that the job of
threadProcessis so short that the first thread can finish before the second thread can get initialized.Put a delay in your loop and you will see the threads working at the same time.