Reputation: 13
I am running trying to run two sub routines at once in perl. What is the best way I can about doing that? For example:
sub 1{
print "im running";
}
sub 2{
print "o hey im running too";
}
How can I execute both routines at once?
Upvotes: 1
Views: 2245
Reputation: 35318
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.
Upvotes: 0
Reputation: 37156
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:
use threads::shared;
)use Thread::Queue;
)use Thread::Semaphore;
)See perlthrtut for more information and an excellent tutorial.
Upvotes: 7