【发布时间】:2015-02-07 16:59:32
【问题描述】:
我正在使用Thread::Queue 将数组推送到队列中并使用线程处理其中的每个元素。下面是我的程序的简化版本,用于演示正在发生的事情。
#!/usr/bin/perl
use strict;
use warnings;
use threads;
use threads::shared;
use Thread::Queue;
# Define queue
my $QUEUE :shared = new Thread::Queue();
# Define values
my @values = qw(string1 string2 string3);
# Enqueue values
$QUEUE->enqueue(@values);
# Get thread limit
my $QUEUE_SIZE = $QUEUE->pending();
my $thread_limit = $QUEUE_SIZE;
# Create threads
for my $i (1 .. $thread_limit) {
my $thread = threads->create(\&work);
}
# Join threads
my $i = 0;
for my $thread (threads->list()) {
$thread->join();
}
print "COMPLETE\n";
# Thread work function
sub work {
while (my $value = $QUEUE->dequeue()) {
print "VALUE: $value\n";
sleep(5);
print "Finished sleeping\n";
}
print "Got out of loop\n";
}
当我运行此代码时,我得到以下输出,然后它就永远挂起:
VALUE: string1
VALUE: string2
VALUE: string3
Finished sleeping
Finished sleeping
Finished sleeping
一旦队列到达终点,while 循环应该中断,脚本应该继续,但它似乎永远不会退出循环。
为什么会卡住?
【问题讨论】:
标签: multithreading perl queue infinite-loop