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

标签 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() 很困惑

最佳答案

你不能在线程实例 $t2->exit() 上调用 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');

关于linux - 当另一个线程在 Perl 中停止时停止一个线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22832829/

相关文章:

perl - 删除 Perl 脚本中的 Windows 符号链接(symbolic link)?

linux - 无法插入 'nvidia_352' : No such device

linux - 如何在 Unix 和 Linux 中将多个命令通过管道传输到一个命令中

java - 使用多线程读取单个文件

java - 当两个线程同时调用同一个静态方法时会发生什么?

windows - Perl 不接收命令行参数?

linux - 如何使用 awk 显示文本文件中的某些特定字段?

linux - 将单词放到行中的特定位置

multithreading - 为什么不能在同一线程上执行多个 pthread_join?

perl - File::Spec 真的有必要吗?