【发布时间】:2014-10-04 06:41:29
【问题描述】:
我制作了一个 Perl 脚本,在其中创建线程(同时运行的线程受到限制),每个线程创建自己的子节点,这些子节点的数量也应该受到限制。
在我托管我的脚本的地方,我不能同时为每个 Perl 脚本启动超过 X 个线程。在下面的示例中,我同时最多有 X = 3 x 7 = 21 个线程。
- 第一份工作 3 (
$nb_process_first) - 第二份工作 7 (
$nb_process_second)
问题:
- 是否有更好的方法来管理线程及其子项? (例如队列 - 请给我一些代码示例,因为我尝试过但没有成功)
- 尽管我在所有正在运行的线程上使用循环来加入它们(参见脚本末尾),但我当前的脚本并未终止并加入所有线程。
#!/usr/bin/perl -s
use threads;
my @threads;
my $nb_process_first = 3;
my @running = ();
print "START" . "\n";
$current = 1;
while ( $current <= 10 ) {
@running = threads->list(threads::running);
if ( scalar @running < $nb_process_first ) {
print "Launch firstJob=" . scalar @running . "\n";
my $thread = threads->create( \&firstJob );
push( @threads, $thread );
} else {
redo;
}
$current++;
}
my @joinable = threads->list(threads::joinable);
while ( scalar @joinable != 0 ) {
foreach my $thr ( threads->list() ) {
$thr->join();
}
@joinable = threads->list(threads::joinable);
}
print "END" . "\n";
sub secondJob {
for ( $i = 0; $i <= 15; $i++ ) {
print "secondJob=" . $i . "\n";
sleep 1;
}
threads->exit();
}
sub firstJob {
my $nb_process_second = 7;
my @running = ();
$current = 1;
while ( $current <= 10 ) {
@running = threads->list(threads::running);
if ( scalar @running < $nb_process_second ) {
print "firstJob/Launch secondJob=" . scalar @running . "-" . $current . "\n";
my $secondthread = threads->create( \&secondJob );
push( @threads, $secondthread );
sleep 2;
}
$current++;
}
threads->exit();
}
【问题讨论】:
标签: multithreading perl