#!/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;
}
perl的多线程脚本示例
最新推荐文章于 2024-07-23 20:14:10 发布