多线程 – Perl线程:如何制作一个制作人?
发布时间:2020-05-25 13:47:28 所属栏目:Java 来源:互联网
导读:我有一个运行速度很慢的功能.我需要在程序的主要部分输入该函数.所以我想做一些类似于UNIX命令的东西,它产生尽可能多的输入,但只需要多一点.不像是,我不想要STDIN的值,但我想要Perl队列中的值. 换句话说:这个问题不是关于文件句柄的选择,而是关于线程维护的
|
我有一个运行速度很慢的功能.我需要在程序的主要部分输入该函数.所以我想做一些类似于UNIX命令的东西,它产生尽可能多的输入,但只需要多一点.不像是,我不想要STDIN的值,但我想要Perl队列中的值. 换句话说:这个问题不是关于文件句柄的选择,而是关于线程维护的队列. 我想,元代码看起来与此类似: my $DataQueue = Thread::Queue->new();
my @producers;
my $no_of_threads = 10;
for (1..$no_of_threads) {
push @producers,threads->create(&producer);
}
for(<>) {
# This should block until there is a value to dequeue
# Maybe dequeue blocks by default - then this part is not a problem
my $val = $DataQueue->dequeue();
do_something($_,$val);
}
# We are done: The producers are no longer needed
kill @producers;
sub producer {
while(1) {
# How do I wait until the queue length is smaller than number of threads?
wait_until(length of $DataQueue < $no_of_threads);
$DataQueue->enqueue(compute_slow_value());
}
}
但有更优雅的方式吗?我特别不确定如何以有效的方式执行wait_until部分. 解决方法像这样的东西可能会起作用:my $DataQueue = Thread::Queue->new();
my @producers;
my $no_of_threads = 10;
for (1..$no_of_threads) {
push @producers,threads->create(&producer);
}
$DataQueue->limit = 2 * $no_of_threads;
for(<>) {
# This blocks until $DataQueue->pending > 0
my $val = $DataQueue->dequeue();
do_something($_,$val);
}
# We are done: The producers are no longer needed
kill @producers;
sub producer {
while(1) {
# enqueue will block until $DataQueue->pending < $DataQueue->limit
$DataQueue->enqueue(compute_slow_value());
}
} (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
