1

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?

jtime08
  • 13
  • 3

2 Answers2

7

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
  • 36,680
  • 16
  • 86
  • 155
  • 1
    See [this post](http://stackoverflow.com/questions/2423353/can-we-run-two-simultaneous-non-nested-loops-in-perl) for a related question. – Zaid Jun 01 '10 at 13:36
0

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.

tsee
  • 5,034
  • 1
  • 19
  • 27
d11wtq
  • 34,788
  • 19
  • 120
  • 195
  • Here's a slightly more easy to follow link: http://perldoc.perl.org/perlthrtut.html#Thread-Basics – d11wtq Jun 01 '10 at 13:16
  • 3
    d11wtq, please edit your answer: the `Thread` module (capital T) does not even work anymore, been long superseded by the `threads` module. – daxim Jun 01 '10 at 15:07
  • 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 Jun 01 '10 at 16:18
  • 1
    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 Jun 01 '10 at 22:44