gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 12:32:26 25 4
gpt4 key购买 nike

您好,我正在尝试停止或在 $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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com