PERL 多进程与多线程编程能大大加快程序执行效率(将一个任务分割成若干小任务并行处理)。要进行多进程和多线程编程则分别需要两个模块, fork()和Threads,然而fork()则为PERL内置函数,因此,只需安装Threads模块(如需变量共享,还需安装Thread::Shared模块)。安装方法如下:
1)Win+R, 打开运行:
2)在运行中输入:cmd 进入DOS环境
3)在DOS下,输入“perl -e "use Threads"”,如果没有报错,则不需安装Threads模块(可跳过4-5)。
4)安装Threads,在DOS下,输入"cpan", 按下Enter键, 直到出现”CPAN>“,如下图:
5)在CPAN提示符后输入”install Threads“. 直到再次出现CPAN提示符,然后输入”exit“ 退出cpan,进入DOS中。最后按第3步再次测试Threads是否安装成功!
一、perl 多进程编程
#!/usr/bin/perl
use strict;
use warnings;
my $Max_pro =10;
for (my $i = 1; $i < $Max_pro; ++$i){
my $child_pro = fork(); #创建进程
if (!defined($child_pro)){
die "launching child $child_pro\n";
}
if ($child_pro == 0 ){
do_child($i,$$);
exit 0;
}
}
exit 0;
sub do_child{
my ($i,$id) = @_;
print "CHILD process $i ===>>> $id\n";
}
二、perl 多线程
foreach my $thread (@threads) {
}
#!/bin/perl
use
threads;
use
threads::shared;
# 涉及到一些进程间变量的共享,用这个模块
my
$process
= 4;
my
$child_num
= 0;
print
$threads::VERSION
.
chr
(10);
while
(1) {
if
(
$child_num
<
$process
){
my
$params
=
$child_num
.
':..........'
;
my
$thr
= threads->create(\
&start_thread
,
$params
);
$child_num
++;
}
#foreach my $t(threads->list()){
foreach
my
$t
(threads->list(threads::joinable)){
$t
->
join
();
}
# all tasks done and no running child, then exit
if
(
$child_num
==4){
exit
;
}
}
sub
start_thread(){
# do actually task here
my
$param
=
shift
;
print
$param
.
chr
(10);
}
Example 3.
#!/usr/local/bin/perl
use
@domain
for
}
print
my
my
my
my
sub
{
}