Ole*_*nge 7 perl multithreading
我有一个运行速度很慢的功能.我需要在程序的主要部分输入该函数.所以我想做一些类似于UNIX命令的东西yes,它产生尽可能多的输入,但只需要多一点.不像yes我不想要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());
}
}
Run Code Online (Sandbox Code Playgroud)
但有更优雅的方式吗?我特别不确定如何以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());
}
}
Run Code Online (Sandbox Code Playgroud)