Hi all.
In the following code:
#!/usr/bin/perl -w
use strict;
use threads qw( yield );
my $thread1 = threads->new(\&sub1);
my $thread2 = threads->new(\&sub2);
my @data = $thread1->join;
print "'Thread1' returned @data";
my @data2 = $thread2->join;
print "'Thread2' returned @data2";
sub sub1 {
yield;
sleep 1;
print "I'm a perl programmer!\n";
return "Threading in perl is fun!\n";
}
sub sub2 {
print "I like computing!\n";
return "Computing is cool!\n";
}
It seems I am unable to obtain different output ( thread1 always executes first even if I include the yield function inside of it ) unless I include a quantity of sleep time in sub1. Isn't that the purpose of 'yield' ( to give up it's CPU time to another thread )? This is my first exposure to perl threads so I apologize if this posting is overly simplistic.
Sample output without using sleep ( win98 - ActiveState 5.8.0 build ):
C:\Perl\bin\hw>perl pg5.pl
I'm a perl programmer!
I like computing!
'Thread1' returned Threading in perl is fun!
'Thread2' returned Computing is cool!
C:\Perl\bin\hw>perl pg5.pl
I'm a perl programmer!
I like computing!
'Thread1' returned Threading in perl is fun!
'Thread2' returned Computing is cool!
C:\Perl\bin\hw>perl pg5.pl
I'm a perl programmer!
I like computing!
'Thread1' returned Threading in perl is fun!
'Thread2' returned Computing is cool!
C:\Perl\bin\hw>perl pg5.pl
I'm a perl programmer!
I like computing!
'Thread1' returned Threading in perl is fun!
'Thread2' returned Computing is cool!
C:\Perl\bin\hw>
Sample output with sleep and yield:
C:\Perl\bin\hw>perl pg5.pl
I like computing! *pause for 1 second*
I'm a perl programmer!
'Thread1' returned Threading in perl is fun!
'Thread2' returned Computing is cool!
C:\Perl\bin\hw>perl pg5.pl
I like computing!
I'm a perl programmer!
'Thread1' returned Threading in perl is fun!
'Thread2' returned Computing is cool!
C:\Perl\bin\hw>perl pg5.pl
I like computing!
I'm a perl programmer!
'Thread1' returned Threading in perl is fun!
'Thread2' returned Computing is cool!
C:\Perl\bin\hw>
From what I understand, perl 6 is going to include an improved thread model. Very interesting indeed.
Thanks,
-Katie.