简体   繁体   中英

How to end a thread in perl

I am new to perl and i have a question about perl thread.

I am trying to create a new thread to check if the running function is timed out, and my way of doing it is as below.

Logic is 1.create a new thread 2.run the main function and see if it is timed out, if ture, kill it

Sample code:

$exit_tread = false;      # a flag to make sure timeout thread will run
my $thr_timeout = threads->new( \&timeout );  
execute main function here;                

$exit_thread = true       # set the flag to true to force thread ends
$thr_timeout->join();      #wait for the timeout thread ends

Code of timeout function

sub timeout
{

$timeout = false;
my $start_time = time();
while (!$exit_thread)
{

    sleep(1);                 
    last if (main function is executed);

    if (time() - $start_time >= configured time )
    {
        logmsg "process is killed as request timed out";
        _kill_remote_process();
        $timeout = true;   
        last;         
    }
}    
}

now the code is running as i expected, but i am just not very clear if the code $exit_thread = true works because there is a "last" at the end of while loop.

Can anybody give me a answer?

Thanks

assuming that the correct pseudo code is this:

sub timeout
{

$timeout = false;
my $start_time = time();
#$timeout instead of $exit_thread 
while (!$timeout)
{

    sleep(1);                 
    last if (main function is executed);

    if (time() - $start_time >= configured time )
    {
        logmsg "process is killed as request timed out";
        _kill_remote_process();

        $timeout= true;   
        last;         
    }
}    
}

Then, no, calling last will not set the $timeout variable - it will simply leave the loop from the point of calling it.

Is this answering your question?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM