Multithreading Perl线程中断睡眠不工作
我想理解,因为如果我运行这段代码Multithreading Perl线程中断睡眠不工作,multithreading,perl,sleep,Multithreading,Perl,Sleep,我想理解,因为如果我运行这段代码 #!/usr/bin/perl use strict; use warnings FATAL => 'all'; use threads; use threads::shared; sub mythread { my $end = 0; # Thread termination variable while(!$end) { eval { local $SIG{'ALRM'} = sub {
#!/usr/bin/perl
use strict;
use warnings FATAL => 'all';
use threads;
use threads::shared;
sub mythread {
my $end = 0; # Thread termination variable
while(!$end) {
eval {
local $SIG{'ALRM'} = sub {
print "SIGALARM received\n";
$end = 1;
die "Alarm!\n";
};
sleep(5); # Wait
};
die $@ unless $@ eq "Alarm!\n";
}
}
my $end = 0; # Main termination variable
$SIG{'INT'} = sub {
$end = 1; # Set Main termination variable
};
my $thr = threads->create( \&mythread );
while(!$end) {
sleep(1);
print "1 second passed\n";
}
print "Send SIGALARM to thread\n";
$thr->kill( "SIGALRM" );
print "Main Wait for thread end\n";
$thr->join();
如果我按CTRL-C键,主线程会正确捕获信号,但当将信号发送到mythread sleep时,不会终止,而是等待5秒钟,即使我将代码包装成一个eval,如所说。信号只能发送到进程,而不能发送到线程。从
$thread->kill
的文档中:
警告:此模块提供的线程信号发送功能实际上并不通过操作系统发送信号。它在Perl级别模拟信号,以便在适当的线程中调用信号处理程序。例如,发送$thr->kill('STOP')
实际上并不挂起线程(或整个进程),而是导致在该线程中调用$SIG{'STOP'}
处理程序(如上所示)
操作系统对您的请求一无所知,因此您的睡眠不会被中断
在这种情况下,您可以使用如下内容:
use Time::HiRes qw( );
sub polling_sleep {
my ($dur) = @_;
my $until = Time::HiRes::time() + $dur;
while (1) {
$dur = $until - Time::HiRes::time();
last if $dur < 0;
Time::HiRes::sleep($dur < 0.5 ? $dur : 0.5);
}
}
polling_sleep(5);
使用时间::雇佣qw();
亚轮询睡眠{
我的($dur)=@;
my$Till=Time::HiRes::Time()+$dur;
而(1){
$dur=$until-Time::HiRes::Time();
如果$dur<0,则为最后一个;
时间:雇佣:睡眠($dur<0.5?$dur:0.5);
}
}
睡眠调查(5);
没有普遍的解决办法