understanding thread in perl

Hi all,

I am trying to build threads which will go to localhost and list the files in given folder.

#!/usr/bin/perl
use threads;
        my $t1 = threads->new(\&sub1, 1);
        my $t2 = threads->new(\&sub2, 2);
     push(@threads,$t1);
      push(@threads,$t2);
 
foreach (@threads) {
my $num = $_->join
} 
 
sub sub1 {
        print "-----started thread 1-----\n";
        system("ssh localhost ls -l /home/user1");
        print "*****done with thread 1*****\n";
        return 1;
sub sub2 {
        print "-----started thread 2-----\n";
        system("ssh localhost ls -l /home/user2");
        print "*****done with thread 2*****\n";
        return 2;
}

I will be very greatfull if someone can explain me the working of BOLD portion and why are they necessory.
If we remove them, perl will simply exit saying 2 threads started 0 unjoined . and will not list the files.

I am using bash Linux bash shell.

push (@threads, $t1) and push (@threads, $t2) ==> This will create thread objects and push its references into array @threads.

join() will give you the return value from a thread. I see that from each thread you're storing the return value into $num, but not making any use of it.

There're few errors in your program. I'm sure that was a typo-error. Here's another version of your program:

#!/usr/bin/perl
use threads;
my $t1 = threads->new(\&sub1, 1);
my $t2 = threads->new(\&sub2, 2);
push(@threads,$t1);
push(@threads,$t2);
 
foreach (@threads) {
    my $num = $_->join();
    print "$num\n";
} 
 
sub sub1 {
        print "-----started thread 1-----\n";
        system("ssh localhost ls -l /home/user1");
        print "*****done with thread 1*****\n";
        return 1;
}
sub sub2 {
        print "-----started thread 2-----\n";
        system("ssh localhost ls -l /home/user2");
        print "*****done with thread 2*****\n";
        return 2;
}
1 Like

thanks for your help sir,

    I did this code in linux but now i am trying to run it on sunOS and its giving me error could not find threads.pm in @INC.

    Do I have to install something so that it will run....?

You may need to install the threads module.

1 Like

This thread module needs perl 5.8 or above. Is there any way i can use threas in perl 5.6.1...???

There is ithreads (interpreter threads) for perl 5.6. Check the perl documentation to see if ithreads are used or the older 5.005 implementation is used in your system.

A good option is to upgrade your installation of perl. Or if you (or your task) are not so keen on performance, you may fork out another process.