gpt4 book ai didi

multithreading - 限制一次运行的线程数

转载 作者:行者123 更新时间:2023-12-03 12:55:59 25 4
gpt4 key购买 nike

考虑一下我必须使用线程来运行大约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";

或您还有其他方法吗?每个子例程将执行不同的任务。

最佳答案

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;
}

关于multithreading - 限制一次运行的线程数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21145384/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com