多线程 – Perl线程:如何制作一个制作人?

前端之家收集整理的这篇文章主要介绍了多线程 – 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());
   }
}
原文链接:https://www.f2er.com/java/129250.html

猜你在找的Java相关文章