A multi-threaded command executor that runs commands in parallel using 4 threads. Reads commands from a file or stdin, queues them, and executes them concurrently using Perl threads. Useful for parallelizing batch operations and improving performance on multi-core systems.
perl mt_run.pl [command_file]
# or pipe commands:
echo "command1\ncommand2" | perl mt_run.pl
Reads commands from file or stdin and executes them in parallel using 4 worker threads.
#!/usr/bin/perl
#
use threads;
use threads::shared;
use Thread::Queue;
my $commands = new Thread::Queue;
my $numthreads = 4; # for 4 cores
sub runCommand {
my $tid = threads->self->tid();
print "thread [$tid] started!\n";
while (my $command = $commands->dequeue) {
system($command);
}
print "thread [$tid] finished!\n";
}
if (++$#ARGV and -e $ARGV[0] and open FILE, "<$ARGV[0]") {
while () {
$commands->enqueue($_);
}
} else {
while () {
$commands->enqueue($_);
}
}
for my $i (1..$numthreads) {
$thread[$i] = threads->new(\&runCommand);
$commands->enqueue(undef);
}
for my $i (1..$numthreads) {
$thread[$i]->join;
}
exit(0);