Perl 线程无法启动



我需要一些帮助,我不知道为什么我的线程不想启动。我没有使用perl的经验,我被要求制作一个逐行处理文件的脚本。根据行的不同,进程应该并行执行其他函数(不在代码段中)、在新文件上调用相同的函数或在新文件(线程)上调用相同函数。

下面,我粘贴了一段实际代码(删除了不相关的代码)。

我正在一个名为"test"的函数上测试多线程部分,该函数应该打印"ok"。

进程执行正确,打印"开始",但随后它被卡住,经过短暂的延迟后,进程完全停止执行。

非常感谢任何能帮助我的人!

use strict;
use warnings;
use IO::Prompter;
use Getopt::Long;
use Log::Message::Simple;
use File::Basename;
use File::Spec;
use IO::Socket::INET;
use UUID::Tiny ':std';
use threads;
use threads::shared;
# *bunch of code deleted*
process_file( $cmdline{csvfile}, 1 );
sub test {
    print "okn";
}
sub process_file {
    # get parameters
    my ( $input_file, $flowid ) = @_;
    # init variables
    # open input file
    open( my $fh, '<:encoding(UTF-8)', $input_folder . $input_file )
        or die "Could not open file '$input_file' $!";
    # process file
    while ( my $row = <$fh> ) {
        chomp $row;
        @request   = split ";", $row;
        $flow_type = $request[0];
        $flow      = $request[1];
        # *bunch of code deleted*
        $filename    = "$flow.csv";
        $keep_flowid = $request[2];                       # keep flowid?
        $tmp_flowid  = $keep_flowid ? $flowid : undef;    # set flowid
        $thread      = $request[3];
        if ( $thread == 1 ) {
            ### Create new thread
            print "startn";
            my $process_thread = threads->create("test");
            $process_thread->join();
        }
        elsif ( $thread == 0 ) {
            # wait on process to complete
            process_file( $filename, $tmp_flowid );
        }
        # *bunch of code deleted*
    }
    # close file
    close $fh or die "Couldn't close inputfile: $input_file";
}

很难说你有这个问题的确切原因——主要的可能性似乎是:

    $thread = $request[3];
    if ($thread == 1){

这是来自文件句柄的输入,所以真正的可能性是"$request[3]"实际上不是1

不过我有点怀疑——你的代码在顶部是use strict; use warnings,但你没有用my声明例如$thread$flow等。这要么意味着你没有使用strict,要么你在重用变量——这是一个很好的方法来结束恼人的故障(比如这个)。

但就目前情况而言,我们不能肯定地告诉你,因为我们无法重现问题来测试它。为了做到这一点,我们需要一些样本输入和MCVE

要扩展评论中关于线程的观点,你可能会看到他们"不受鼓励"的警告。这主要是因为perl线程与其他语言中的线程不同。它们不是轻量级的,在其他语言中它们是轻量级的。它们是解决特定类别问题的完全可行的解决方案,特别是那些需要与比基于fork的并发模型更多IPC并行的问题。

我怀疑您遇到了这个错误,该错误已在Perl5.24中修复。

如果是这样的话,您可以通过执行自己的解码而不是使用编码层来解决它。

最新更新