user3363754
user3363754

Reputation: 61

Stop a thread when another thread stops in Perl

Hi I am trying to stop or kill the thread $t2 when $t1 stops. Here is the code:

#!/usr/local/bin/perl

use strict;
use warnings;
use threads;
use threads::shared;
use Time::HiRes qw( sleep );

print "Starting main program\n";

my @threads;
my $t1 = threads->new(\&c1);
my $t2 = threads->new(\&progress);
#my $t2 = threads->new(\&c2);
push(@threads,$t1);
push(@threads,$t2);

my $ret1 = $t1->join();
print "Thread returned: $ret1\n";
$t2->join();


if (!($t1->is_running()))
{
    $t2->exit();
}

print "End of main program\n";

sub c1
{
    print "Inside thread 1\n";
    sleep 5;
    return 245;
}
sub c2
{
    print "Inside thread 2\n";
}
sub progress
{
    $| = 1;  # Disable buffering on STDOUT.

    my $BACKSPACE = chr(0x08);

    my @seq = qw( | / - \ );
    for (;;) {
       print $seq[0];
       push @seq, shift @seq;
       sleep 0.200;
       print $BACKSPACE;
    }

    print "$BACKSPACE $BACKSPACE";
}

But thread $t2 continues running. Please help me out with this. How to kill thread $t2.

I am confused with join(), detach(), exit()

Upvotes: 2

Views: 149

Answers (2)

perreal
perreal

Reputation: 97918

You can use a shared variable:

use threads::shared;    
my $done : shared;
$done = 0;
my $t1 = threads->new( sub { c1(); $done = 1;} );

And in the progress function:

# ...
for (;!$done;) {
# ....

Upvotes: 0

mpapec
mpapec

Reputation: 50637

You can't call exit on thread instance $t2->exit() and module warns you about that,

perl -Mthreads -we '$_->exit(3) and $_->join for async {sleep 4}'
Usage: threads->exit(status) at -e line 1
Perl exited with active threads:
    1 running and unjoined
    0 finished and unjoined
    0 running and detached

However, you can send a signal to thread (check signal list)

# Send a signal to a thread
$thr->kill('SIGUSR1');

Upvotes: 1

Related Questions