gpt4 book ai didi

multithreading - 为什么我的 Perl 线程陷入无限循环? (线程::队列)

转载 作者:行者123 更新时间:2023-12-04 04:31:19 25 4
gpt4 key购买 nike

我正在使用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 循环应该中断,脚本应该继续,但它似乎永远不会脱离循环。

为什么会卡住?

最佳答案

由于您从未调用 $QUEUE->end(),因此您的线程在 dequeue() 上阻塞,等待更多条目出现。

因此,请确保在最后一次调用入队之后或加入线程之前调用 $QUEUE->end()

关于multithreading - 为什么我的 Perl 线程陷入无限循环? (线程::队列),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27385091/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com