Perl running simultaneous routines
I am running trying to run two sub routines at once in perl. What is the best way I can about d开发者_如何学运维oing that? For example:
sub 1{
print "im running";
}
sub 2{
print "o hey im running too";
}
How can I execute both routines at once?
Use threads
.
use strict;
use warnings;
use threads;
sub first {
my $counter = shift;
print "I'm running\n" while $counter--;
return;
}
sub second {
my $counter = shift;
print "And I'm running too!\n" while $counter--;
return;
}
my $firstThread = threads->create(\&first,15); # Prints "I'm running" 15 times
my $secondThread = threads->create(\&second,15); # Prints "And I'm running too!"
# ... 15 times also
$_->join() foreach ( $firstThread, $secondThread ); # Cleans up thread upon exit
What you should pay attention to is how the printing is interleaved irregularly. Don't try to base any calculations on the false premise that the execution order is well-behaved.
Perl threads can intercommunicate using:
- shared variables (
use threads::shared;
) - queues (
use Thread::Queue;
) - semaphores (
use Thread::Semaphore;
)
See perlthrtut for more information and an excellent tutorial.
I actually didn't realise that Perl can do this, but what you need is multithreading support:
http://search.cpan.org/perldoc?threads
Either that, or fork two processes, but that would be a bit harder to isolate the invocation of the subroutine.
精彩评论