tjw*_*992 2 queue perl multithreading infinite-loop
我正在使用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";
}
Run Code Online (Sandbox Code Playgroud)
当我运行此代码时,我得到以下输出,然后它永远挂起:
VALUE: string1
VALUE: string2
VALUE: string3
Finished sleeping
Finished sleeping
Finished sleeping
Run Code Online (Sandbox Code Playgroud)
一旦队列到达终点,while循环应该中断并且脚本应该继续,但它似乎不会离开循环.
为什么会卡住?
由于您从未调用过$QUEUE->end(),因此您的线程在dequeue()等待显示更多条目时会阻塞.
因此,确保$QUEUE->end()在最后一次入队调用之后或加入线程之前进行调用.
| 归档时间: |
|
| 查看次数: |
393 次 |
| 最近记录: |