updated git and svn scripts
[xrzperl.git] / exec_threads
blob88bf34a5975705535c732bd5b0b07458b8475016
1 #!/usr/bin/perl -w
2 ###APPNAME: exec_threads
3 ###APPAUTHOR: xiaoranzzz
4 ###APPDATE: Wed Mar 26 15:10:05 2008
5 ###APPVER: 0.1
6 ###APPDESC: execute cmds using threads
7 ###APPUSAGE: (Number of threads)
8 ###APPEXAMPLE: cat cmd.lst | exec_threads 3
9 ###APPOPTION:
10 use strict;
11 use threads;
13 $ARGV[0]="-h" unless(@ARGV);
14 foreach(@ARGV){
15 exit(system("plhelp",$0,@ARGV)) if($_ eq "-h" || $_ eq "--help");
18 my $max=shift;
19 die("Number must greater than 0\n") unless($max>0);
21 sub process {
22 my $idx=shift;
23 $idx++;
24 print STDERR "\n[Thread $idx]",@_,"\n";
25 my $r=(system(@_));
26 threads->exit($r);
27 return $r;
30 sub waitfor {
31 my @ths=@_;
32 while(1) {
33 my $idx=0;
34 foreach my $t(@ths) {
35 return $idx unless(defined($t));
36 if($t->is_joinable) {
37 $t->join();
38 return $idx;
40 $idx++;
42 sleep 1;
46 my @ths;
47 while(<STDIN>) {
48 chomp;
49 my $cmd=$_;
50 my $idx;
51 next unless($cmd);
52 if(@ths>=$max) {
53 $idx=waitfor(@ths);
54 # print "\n[Thread:",($idx+1),"] End\n";
55 $ths[$idx]=threads->create(\&process,$idx,$cmd);
57 else {
58 $idx=@ths;
59 my $hnd=threads->create(\&process,$idx,$cmd);
60 push(@ths,$hnd);
62 # print "\n[Thread:",($idx+1),"] Start: $cmd\n";
63 # print STDERR "\n\n[T",($idx+1),"]:$cmd\n";
66 for(my $i=0;$i<@ths;$i++) {
67 next unless($ths[$i]);
68 next unless($ths[$i]->is_running() or $ths[$i]->is_joinable());
69 $ths[$i]->join();
70 # print "\n[Thread:",($i+1),"] End\n";