当另一个线程在Perl中停止时停止一个线程

时间:2014-04-03 09:07:53

标签: linux multithreading perl

嗨我试图在$ t1停止时停止或杀死线程$ t2。这是代码:

#!/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";
}

但是线程$ t2继续运行。这个你能帮我吗。 如何杀死线程$ t2。

我对join(),detach(),exit()

感到困惑

2 个答案:

答案 0 :(得分:1)

您无法在线程实例exit上调用$t2->exit(),模块会向您发出警告,

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

但是,您可以send a signal进行线程化(检查signal list

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

答案 1 :(得分:0)

您可以使用共享变量:

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

在进度函数中:

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