Core iTOps Tube

Thursday, 26 April 2012

using threads in perl

Hi everyone,



I am trying to create a script which runs a number of processes simultaneously and at the same time use a timer to keep track of what is going on.



The problem is that the timer stops and the script exits upon the completion of some of the processes, whereas I want to timer to continue indefinitely.



Note that the functionality of the file transfer and file size monitoring all works as required, the problem is only with the timer not continuing after the file has been completely sent. I want to add subsequent files so it is important that the timer continues.



Here is some code:


Code:


#!/usr/bin/perl

use strict;

use warnings;

use threads;

use Time::HiRes qw(usleep nanosleep);



my @downloadingFiles = ();

my $fileNumber = 0;

my $overallTimer = 0;

my $fileSize = 0;

my $temp1 = 0;

my $temp2 = 0;



#this is my timer which should run until 1000, but it actually stops when setupSenderAndReceiver function has terminated. It is monitoring the file size of the file which is being transferred through the socket.

sub GlobalTimer        {

        while($overallTimer <= 1000)        {

        $overallTimer++;

        sleep(1);

        $fileSize = -s "out$fileNumber";

        @downloadingFiles[$fileNumber] = $fileSize;

        $print "$overallTimer";

                                        }

                }



#this function uses two functions inside it to establish a server and client connection and send a file through a socket.

sub setupSenderAndReceiver{

$temp1 = $_[0];

$temp2 = $_[0];



#this script opens the server port

sub first {

system("/usr/bin/perl myPerlScript2.pl $temp1");

}



#this sends a command to a remote machine to start sending data.

sub second {

my @x = ("bash", "-c", "ssh ip_address_and_details_removed $temp2");

system(@x);

}



#this should instruction both processes to run at the same time and exit the thread upon completion.

my $firstThread = threads->create(\&first);

my $secondThread = threads->create(\&second);

firstThread->join();

secondThread->join();

}



#this is the thread I used to start the overall timer

my $globalT = threads->create(\&GlobalTimer);

$globalT->detach();

#this is the thread I used to create the file transfer

my $start = threads->create(\&setupSenderAndReceiver, $fileNumber);

$start->join();


Thanks in advance.



---------- Post updated at 04:38 PM ---------- Previous update was at 07:26 AM ----------



Uppies




No comments:

Post a Comment