perl的多线程脚本示例

#!/usr/bin/perl -w

use strict;
use Data::Dumper;
use POSIX;
use Getopt::Long;
use threads ('exit' => 'threads_only');
use List::Util 'shuffle';
use Thread::Semaphore;
use threads::shared;
use File::Basename;

##设置并行线程数
my $semaphore_cnt = Thread::Semaphore->new(100);

my @hosts = ();

open (HOSTFILE,"</home/hdfs/lxw/mapred.hosts") or die "failed to open hostfiles to read\n";
while (<HOSTFILE>) {
	chomp;
	push @hosts,$_;
}
close HOSTFILE;


foreach my $host (@hosts) {
		$semaphore_cnt->down();
		my $t = threads->create(\&deleteFiles,$host);
		foreach my $thr (threads->list(threads::joinable)){
			$thr->join();
		}
}


foreach my $thr (threads->list()){
    $thr->join();
}

sub deleteFiles() {
	my $host = $_[0];
	my $command = qq(source /etc/profile
		source /etc/bashrc
		ssh $host -p 58422 -t 'sudo nohup sh /tmp/del.sh'
);
	my $start_time = &getNowTime();
	my $result = system($command);
	my $end_time = &getNowTime();
	if ("$result" eq "0") {
		&wirteLog($host . "  start:" . $start_time . " end:" . $end_time . "\n");
		$semaphore_cnt->up();
	} else {##failed
		$semaphore_cnt->up();	
	}
}


sub getNowTime {
    my ($sec,$min,$hour,$day,$mon,$year) = (localtime(time))[0,1,2,3,4,5];
    sprintf "%4d-%02d-%02d %02d:%02d:%02d",$year+1900,$mon+1,$day,$hour,$min,$sec;
}

sub wirteLog {
	my ($msg) = @_;
	my $logFile = "/tmp/delete_tobedeleted.log";
	open LOGFILE,">>$logFile" or die "failed to open $logFile to write\n";
	print LOGFILE $msg;
	close LOGFILE;
}
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值