多个进程同时运行

时间:2013-08-07 18:06:44

标签: perl

我使用perl脚本执行一个脚本,该脚本应该同时执行10个不同的进程。我的要求是: 1.它将首先从文本文件中提取每一行(每行有10行,每行一个单词) 2.使用此行来为所有这些名称提取一个脚本app.exe。 3.执行应该同时执行的每个线程。

为了实现这一点,我已经写下了一段代码。但是我可以看到任务管理器中一次只运行一个进程。但我需要所有10个进程应该同时运行。有人可以帮我这个吗?

use Thread; 
$file='input.txt'; 
open(INFO, $file) or die("Could not open file."); 
$count = 0; 
foreach $line (<INFO>) { $huh = Thread->new(\&thread1); 
print "Waiting for thread now\n"; 
$stuff = $huh->join(); 
sub thread1 { print "$line"; 
'QueryStores.exe "UPDATE OPTIONS_STR SET OPT_VALUE = 0 WHERE OPT_ID = 16005" /S:$line'    
return 1;} } close(INFO);

2 个答案:

答案 0 :(得分:4)

  1. 您正在创建线程,而不是进程。
  2. 线程未显示在任务管理器中,因此我不确定如何设置使用任务管理来确定一次只运行一个。
  3. 你是对的,你创建的线程中只有一个是一次运行的,因为你在创建另一个之前等待你刚刚创建的线程结束(->join)。
  4. use threads;
    use Thread::Queue 1.03 qw( );
    
    use constant NUM_WORKERS => 10;
    
    sub worker {
       my ($job) = @_;
       system('QueryStores "UPDATE OPTIONS_STR SET OPT_VALUE = 0 WHERE OPT_ID = 16005" /S:'.$job);
       if    ($? == -1)  { warn("Can't start child $job: $!\n"); } 
       elsif ($? >> 8)   { warn("Child $job returned error ".($? >> 8)."\n"); } 
       elsif ($? & 0x7F) { warn("Child $job killed by signal ".($? & 0x7F)."\n"); } 
    }
    
    my $q = Thread::Queue->new();
    for (1..NUM_WORKERS) {
        async {
            while (defined(my $job = $q->dequeue())) {
               worker($job);
            }
        };
    }
    
    while (<>) {
       chomp;
       $q->enqueue($_);
    }
    
    $q->end();
    $_->join() for threads->list();
    

答案 1 :(得分:0)

我试过阅读你的代码,问题似乎是你的线程在下一个循环之前等待加入(阻塞)。任务管理器不显示线程(仅执行)。尝试Process Explorer查看帖子(我没有亲自使用但看起来它可以完成这项工作)

您的代码应该是这样的

#!/bin/perl 

use warnings;
use strict;

use Thread;

my @list = qw(abc1 abc2 abc3 abc4 abc5);
my @threadlist = ();

for my $lst (@list) {
  my $t = Thread->new(\&thread_exec , $lst);
  print "Wating for thread for $lst\n";
  push @threadlist, $t;
}

for my $thd (@threadlist) {
  print "Wating for thread to join\n";
  $thd->join;
}

sub thread_exec {
  my $info = shift;
  print "INFO = $info\n";
}

哪个输出类似[你可以看到线程并行运行]

$~/Documents/dummy.pl 
Wating for thread for abc1
Wating for thread for abc2
Wating for thread for abc3
Wating for thread for abc4
Wating for thread for abc5
Wating for thread to join
INFO = abc2
INFO = abc5
INFO = abc1
Wating for thread to join
Wating for thread to join
INFO = abc4
INFO = abc3
Wating for thread to join
Wating for thread to join

另一方面 - 将连接放在同一个for循环中(就像你已经完成的那样产生一个这样的线程的序列化执行)

$~/Documents/dummy.pl 
Wating for thread for abc1
INFO = abc1
Wating for thread for abc2
INFO = abc2
Wating for thread for abc3
INFO = abc3
Wating for thread for abc4
INFO = abc4
Wating for thread for abc5
INFO = abc5