如何在perl中按需启动线程?

时间:2014-01-23 06:16:22

标签: multithreading perl

在c#中,我们可以根据需要创建线程并启动线程,如下所示(如果我是正确的)

Thread th=new thread("function");
th.start()

但是在perl中,当我创建它时,它已经开始了。例如

$thread1=thread->create("function");

但我想创建4个帖子。我应该只根据需要开始。我还要检查它是否正在运行?如果线程没有运行,那么我通过传递不同的参数来启动相同的线程。如何在perl中做到这一点?

3 个答案:

答案 0 :(得分:2)

可以将多个作业发送到队列中,并等待轮到他们传递给工作人员。

use strict;
use warnings;
use threads;
use Thread::Queue;

my $no_of_workers = 4;
my $q = Thread::Queue->new();
# Worker thread
my @thr = map {

  my $t = threads->create(sub{

    # Thread will loop until no more work
    while (defined(my $item = $q->dequeue())) {
        # Do work on $item
        print "$item\n";
    }
  });

  {queue => $q, thread => $t, id => $_};

} 1 .. $no_of_workers;


# Send work to each thread
$_->{queue}->enqueue("Job for thread $_->{id}") for @thr;

for (@thr) {
  # Signal that there is no more work to be sent
  # $_->{queue}->end();

  # similar to $queue->end() for older perl
  $_->{queue}->enqueue(undef) for @thr;

  # wait for threads to finish
  $_->{thread}->join();
}

以循环方式为工作人员分配工作0..19

for my $i (0 .. 19) {
  my $t = $thr[$i % @thr]; # $i % @thr => 0,1,2,3, 0,1,2,3, ..
  $t->{queue}->enqueue("Job for thread $t->{id}");
}

答案 1 :(得分:0)

您不希望每个线程都有队列!即使工作可用,你也会得到空闲的线程。

use strict;
use warnings;

use threads;

use Thread::Queue 3.01 qw( );

use constant NUM_WORKERS => 4;

sub worker {
   my ($job) = @_;
   print("Job: $job\n");
   sleep(rand(4));  # Pretending to do $job
}

{
   my $q = Thread::Queue->new();

   for (1..NUM_WORKERS) {
      async {
         while (defined(my $item = $q->dequeue())) {
            worker($item);
         }
      };
   }

   # Give the workers work to do.
   $q->enqueue($_) for 1..14;

   # When you're done adding, wait for the workers to finish.
   $q->end();
   $_->join() for threads->list;
}

答案 2 :(得分:0)

此代码只执行4个线程,然后停止。它不会处理队列中剩余的6个项目。