| Refresh | Home EGTry.com

perl thread's blocking queue - dequeue blocking and enqueue is not


use threads;
use Thread::Queue;


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

#queue size is infinite, enqueue never blocks

for (my $i=0; $i<10; $i++) {
  $q->enqueue("item $i");
}
$q->enqueue(undef);
$q->enqueue(undef);

my $consumer1=threads->create(\&consume);
my $consumer2=threads->create(\&consume);


$consumer1->join();
$consumer2->join();


print "done\n";


sub consume {
  my $tid=threads->tid();
  
  my $val;
  while($val=$q->dequeue()) { #dequeue call blocks if the queue is emptry
    print "$tid val=$val\n";
    sleep(rand);
  }
}






Output

1 val=item 0
1 val=item 1
1 val=item 2
1 val=item 3
1 val=item 4
1 val=item 5
1 val=item 6
1 val=item 7
1 val=item 8
1 val=item 9
done