Perl 多线程和 foreach [英] Perl multithreading and foreach

查看:35
本文介绍了Perl 多线程和 foreach的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个简单的 Perl 脚本,它可以同时运行其他 Perl 脚本.我不知道如何让主程序等待正在运行的线程.由于多种原因,睡眠不是合适的解决方案.这是我的主要"脚本:

I am writing a simple Perl script that should run other Perl scripts simultaneously. I don't know how to make the main program wait for running threads. Sleep IS NOT a suitable solution because of many reason. This is my "main" script:

#!/usr/bin/perl
use threads;
main:
{
    if ($#ARGV == -1) { usage(); exit(1); }
    my $hostname = $ARGV[0];
    my $thrssh = threads ->create(\&ssh, $hostname);
    my $thrdns = threads ->create(\&dns, $hostname);
    my $thrping = threads ->create(\&ping, $hostname);
    my $thrsmtp = threads ->create(\&smtp, $hostname);
    my $thrproxy = threads ->create(\&proxy, $hostname);
}
sub ssh {
    threads->detach();
    my $hostname = @_;
    #print "SSH\n";
    #LAUNCH SSH SCRIPT
}
#OTHER SUBROUTINES...
sub proxy {
    threads->detach();
    my $hostname = @_;
    #print "PROXY\n";
    #LAUNCH PROXY SCRIPT
}

如果我尝试运行此脚本,我会注意到的第一件事是打印是连续的",我认为文本被搞乱了,但也许打印是排他性的,我不知道.主要问题是最后两个子程序没有时间执行.

If I try to run this script the first thing I can notice is that prints are "sequential", I thought text was messed up but maybe Print is exclusive I don't know. Main problem is that the last two subroutines don't have time to be executed.

SSH
DNS
PING
Perl exited with active threads:
2 running and unjoined
0 finished and unjoined
0 running and detached

如果我使用 join 而不是 detach 子例程将变为顺序",例如,如果我在 sub ssh 中休眠,其他线程将在启动之前等待.我希望它们是并行的,并且主程序仅在所有线程完成后才关闭,有什么帮助吗?

If I use join instead of detach the subroutines become "sequential", for example if I put a sleep in sub ssh other threads will wait before starting. I want them to be parallel and the main program to close ONLY when all threads are finished, any help?

其实我还有一个问题,当我应该加入它们时,我是否必须在一个 foreach cicle 中运行多个线程?即:

my $thrssh;
foreach $mynode ($nodeset->get_nodelist) {
    #...
    $thrssh = threads ->create(\&ssh, $port, $hostname);
    #...
}
$thssh->join();

是吗?

推荐答案

您需要加入所有线程从主线程启动后.如果您不希望解释器在线程仍在运行时退出,请不要 detatch.

You need to join all your threads from the main thread after they have all been started. Don't detatch if you don't want the interpreter to exit while the threads are still running.

...
my $thrssh = threads ->create(\&ssh, $hostname);
my $thrdns = threads ->create(\&dns, $hostname);
...
$thrssh->join();
$thrdns->join();
...

关于您的不,这是不对的.您需要保留对您创建的每个线程的引用,否则您无法加入它们.

Regarding your edit: no, it's not right. You need to keep a reference to each thread you create, otherwise you can't join them.

做类似的事情:

my @thrs;
foreach $mynode ($nodeset->get_nodelist) {
    #...
    $thrssh = threads ->create(\&ssh, $port, $hostname);
    push @thrs, $thrssh;
    #...
}
$_->join() for @thrs;

这篇关于Perl 多线程和 foreach的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆