multithreading - Perl 中线程的超时

标签 multithreading perl

我正在编写一个 perl 脚本,以便在 5 秒后退出线程,如下所示。但我无法打印 if 条件中的消息。

脚本的输出是闹钟

当线程超时时,如何从父进程打印正确的错误消息。

#!/usr/bin/perl
use strict;
use warnings;
use threads;

my $th   = threads->create( \&sub1 );
my $thid = $th->tid();

eval
{
    $SIG{'KILL'} = sub
    {
        if ( $th->is_running() )
        {
            print "timed out, exiting the thread $thid\n";
            $th->exit();
        }
    };
    alarm(5);
    $th->join();
};

sub sub1
{
    my $i = 0;
    while ( $i == 0 )
    {
    }

}

最佳答案

Documentation says

如果您想使用警报来使系统调用超时,您需要使用 eval/die 对。

或者,您可以使用 Sys::SigAction 并执行如下操作

use Sys::SigAction qw( timeout_call );
if ( timeout_call( 5 ,sub { $retval = DoSomething( @args ); } )
{
   print "DoSomething() timed out\n" ;
}

编辑:参见暴徒对问题的回答:Perl threads with alarm

另请参阅 thread safe alarms 上的讨论.

关于multithreading - Perl 中线程的超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24359316/

相关文章:

perl - Perl 的 Safe 是否了解新功能?

perl - 在 Perl 中打印多键哈希

perl - Perl 的 Data::Dumper 中的 DumpXS 有什么作用?

c# - 并发队列性能不佳

c++ - pthread_create 参数传递错误

c++ - 我是否以线程安全的方式使用这个双端队列?

node.js - 连接到 websocket 时为 "handshake error: Wrong response line"

java - JavaFX Platform.runLater 的使用和从不同线程访问 UI

c++ - G++ 命令行使用线程标记,linux makefile 不使用

perl - 如何对值为数组引用的 Perl 哈希进行排序?