tags:

views:

88

answers:

2

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?

A: 

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.

d11wtq
Here's a slightly more easy to follow link: http://perldoc.perl.org/perlthrtut.html#Thread-Basics
d11wtq
thanks i will have a look into it
jtime08
d11wtq, please edit your answer: the `Thread` module (capital T) does not even work anymore, been long superseded by the `threads` module.
daxim
I edited the answer. d11wtq, I hope you don't mind, but I wanted to make sure we're not spreading any any misleading information.
tsee
Thanks and sorry on my part. I haven't used Perl since university and never needed to do any threading, it was just what came out at the top of a Google search ;) Apologies.
d11wtq
+7  A: 

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.

Zaid
See [this post](http://stackoverflow.com/questions/2423353/can-we-run-two-simultaneous-non-nested-loops-in-perl) for a related question.
Zaid
thanks everyone. appreciate it
jtime08