gpt4 book ai didi

multithreading - 多线程 perl 脚本中的 Control+C 处理

转载 作者:行者123 更新时间:2023-12-02 05:02:55 24 4
gpt4 key购买 nike

我是 perl 新手,在我的 perl 脚本中处理 ^C 时遇到问题。当我在 sleep 期间收到 ^C 后尝试继续执行脚本时,我只在 $FLAG = 2; 之前输出;之后什么都没有:

# perl test.pl 
sleeping...
^Cawaiking... =
#

代替:

# perl test.pl 
sleeping...
awaiking... ====
some..
#

它似乎 ^C 正在终止进度条线程,并且在它终止后没有任何操作,但可以在主线程中执行打印。谁能帮我解决这个问题?

$SIG{INT} = 'IGNORE';
our $FLAG : shared = 1;
...
sub call1{
$FLAG = 1;
my $pBar = threads->new(\&progressBarInit);
$pBar->detach;
print "sleeping...\n";
sleep 5;
print "awaiking...\n";
$FLAG = 2;
print "some..\n";
return @result;
}

call1();

sub progressBarInit{
my $max = 50;
my $counter = 1;
while($FLAG == 1){
progressBar( $counter, $max, 50, '=' );
$counter++;
if($counter > $max){$counter=1;}
sleep 1;
}
}

sub progressBar {
my ( $counter, $max, $width, $char ) = @_;
local $| = 1;
printf " %-${width}s\r", $char x (($width-1)*$counter/$max);
}

最佳答案

我认为问题在于您在父级中设置了信号处理程序。

根据这个:http://perldoc.perl.org/threads.html

Signal handlers need to be set up in the threads for the signals they are expected to act upon. Here's an example for cancelling a thread:

除了使用标志,您还可以使用信号进行通信:

sub progressBarInit    {
# Thread 'cancellation' signal handler
$SIG{'KILL'} = sub { threads->exit(); };
$SIG{INT} = 'IGNORE';
...
}
...
# Signal the thread to terminate, and then detach
# it so that it will get cleaned up automatically
my $pBar = threads->new(\&progressBarInit);
print "sleeping...\n";
sleep 5;
print "awaiking...\n";
$pBar->kill('KILL')->detach();

关于multithreading - 多线程 perl 脚本中的 Control+C 处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14626952/

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