首页 技术 正文
技术 2022年11月15日
0 收藏 603 点赞 3,346 浏览 1081 个字

  关于perl的多进程,大家可能马上会想到Parallel::ForkManager这个模块。但是今天我们试着自己动手写一个类似的框架:)

  该多进程开发模型从开源服务器框架Lighttpd发展而来,核心思路是父进程监控子进程的状态并负责回收,子进程负责任务的执行。当前预先可以设置子进程并发数目的上限值。如需要涉及到进程间的通信,可以通过建立管道pipe的方式,让子进程在结束前将数据通过共享管道写入,待父进程适时读取即可。

   本人在工作中进程遇到这样的场景,如从DB取若干任务,收包等等(不停的取/收),为了保证效率,一般都采取并发执行;使用脚本主要为了轻量级,易部署。这种场景下很适合用这种watcher-worker模式。perl代码如下:

  

 #!/usr/bin/perl -w #author:pandaychen
#date:2015-04-01
#info:实现一个简单的多进程框架 use strict;
use warnings;
use POSIX ":sys_wait_h"; my $max_process = ;
my $cur_process =; my @pid_array; print "perl fork watcher-worker:\n"; #main start here
CreateWorker($max_process); #child start here
do_workers(); sub CreateWorker{
my $workers=shift(@_);
print $workers,"\n"; my $sign = ; while($sign){
if($workers >){
my $pid = fork();
if($pid >){
#watcher
$sign = ;
--$workers;
}
elsif($pid == ){
#workers
$sign = ;
print "create worker ",$$," success!\n" ;
do_workers();
}
else
{
print "fork error: %s\n";
return -;
}
}
else{
#full workers
my $nStatus;
while ((my $collect = waitpid(-, WNOHANG)) > )
{
print $collect," child process\n";
$workers++;
}
}
}
return ;
} sub do_workers{
#模拟子进程工作
my $rand=int(rand());
sleep($rand);
print "child process sleep ",$rand," seconds.\n";
exit();
}

执行结果如下:

Perl的多进程框架(watcher-worker)

下一篇: impdp使用
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,491
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,907
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,740
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,493
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,132
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,294