簡體   English   中英

如何在perl中按需啟動線程?

[英]How to Start thread only on demand in perl?

在c#中,我們可以創建線程並僅在需要時啟動線程如下(如果我是正確的)

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

但是在perl中,當我創建自己時,它已經開始了。 例如

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

但我想創建4個線程。 我應該只根據需要開始。 我要檢查它是否正在運行? 如果線程沒有運行,那么我將通過傳遞不同的參數來啟動相同的線程。 如何在perl中做到這一點?

可以將多個作業發送到隊列中,並等待輪到他們傳遞給工作人員。

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

你不希望每個線程都有一個隊列! 即使工作可用,你也會得到空閑的線程。

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

此代碼僅執行4個線程,然后停止。 它不處理隊列中剩余的6個項目。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM