perl多线程未运行批处理命令



我正在尝试使用perl多线程来运行每个cmd.exe命令,其中包含在一个大型文件中,类似于此:

copy file1.txt file2.txt
copy file3.txt file4.txt
...
copy file5000.txt file5001.txt

我查看了这个问题的答案,并尝试了一个示例测试以复制两个文件。

问题是命令永远不会被调用。即使文件在那里,也不会在我运行perl脚本的同一文件夹中制作副本。

我在做什么错?

use strict;
use warnings;
use threads;
use Thread::Queue; 
print "Perl Starting ... nn"; 
my $q = Thread::Queue->new();    # A new empty queue
# Worker thread
my @thrs = threads->create(&doOperation ) for 1..5;#for 5 threads
my @files = ("copy file123.xml test1.xml", "copy file123.xml test2.xml");
#add files to queue
foreach my $f (@files){
  # Send work to the thread
  $q->enqueue($f);
  print "Pending items: ". $q->pending() ."n";
}
$q->enqueue('_DONE_') for @thrs;
$_->join() for @thrs;

sub doOperation () {
    my $ithread = threads->tid() ;
    while (my $cmd = $q->dequeue()) {
      # Do work on $item
      print "cmd: $cmd ... n";
      print "Running Dos command ... n";
      my $status = system("$cmd");
      print "Status: $status ... n";
      print "End Dos command ... n";
      return 1 if $cmd eq '_DONE_';
      print "[id=$ithread]t$cmdn";
    }
    return 1;
}

print "nPerl End ... nn"; 

…这是cmd.exe

中的输出
Perl Starting ...
Pending items: 1
cmd: copy file123.xml test1.xml ...
Running Dos command ...
Pending items: 0
cmd: copy file123.xml test2.xml ...
Running Dos command ...
Perl End ...
Perl exited with active threads:
        5 running and unjoined
        0 finished and unjoined
        0 running and detached

ps。我已经尝试了Parallel :: Forkmanager,并且在Windows Server上的X处理数量之后,我一直在崩溃,所以这就是为什么我正在寻找替代解决方案。

以下声明会导致@thr的元素为零。

my @thrs = threads->create(&doOperation ) for 1..5;#for 5 threads

然后,您指的是两个地方的@THR。如果您用threads->list()替换所有这些引用为Mobrine指示(不仅是一个参考,而是两个参考),那么您将取得进度。

或您可以这样修复声明:

my @thrs;
push @thrs, threads->create(&doOperation ) for 1..5;

关于您对修复一个参考的问题的评论。


在下面的评论中,假设您需要保留自己的线程列表,Ikegami显示了创建列表的更透明的方法:

my @thrs = map { threads->create(&doOperation ) } 1..5;

最新更新