考虑到我有大约100个子程序,我必须使用线程运行。
如何限制所有线程,以便一次只运行10个线程?你能给我一个示例代码吗?
以下是我需要实现它的示例代码
use threads;
my ($thr1) = threads->create(\&sub1,$parameter);
my ($thr2) = threads->create(\&sub2,$parameter);
...
my ($thr100) = threads->create(\&sub100,$parameter);
my $result;
for my $t(@threads){
#print "$t\n";
(my @getit)= $t->join();
my $tmp = join '', @getit;
$result .= $tmp;
}
print "$result\n";
或者你有其他任何方法吗?每个子程序都会执行不同的任务。
答案 0 :(得分:3)
use threads;
use Thread::Queue 3.01 qw( );
my $NUM_WORKERS = 10;
sub worker {
my ($job) = @_;
my ($sub_name, @args) = @$job;
my $sub_ref = \&$sub_name;
$sub_ref->(@args);
}
{
my $q = Thread::Queue->new();
my @workers;
for (1..$NUM_WORKERS) {
push @workers, async {
while (my $job = $q->dequeue()) {
worker($job);
}
};
}
$q->enqueue($_)
for
[ sub1 => ( @args ) ],
[ sub2 => ( @args ) ];
$q->end();
$_->join() for @workers;
}