【发布时间】:2016-11-25 10:28:14
【问题描述】:
foreach $thr (1..5)
{
$threads[$thr]=threads->create("worker");
}
和
foreach (1..5)
{
push @threads,threads->create("worker");
}
后者运行良好,前者发出警告。
#!/usr/bin/perl
use strict;
use threads;
use threads::shared;
use Thread::Queue;
my $queue = Thread::Queue->new();
my @threads;
my $thr;
#----------------------------------------create
#send work first,and then creat threads, the first thread work earlier.
$queue->enqueue(1..10000);
foreach (1..5)
{
push @threads,threads->create("worker");
}
$queue->end();
sub worker
{
while (my @DataElement = $queue->dequeue(100))
{
my $tid = threads->tid();
#open (my $out,">>$tid.txt") or die $!;
print "Threads ID:$tid\t@DataElement\n";
#print $out "Threads ID:$tid\t@DataElement\n";
#close $out;
}
}
#----------------------------------------cut
my $thr_num=1;
my $i;
while ($thr_num)
{
$i++;
foreach (@threads) #store threads, TRUE even if joined.
{
$thr_num = threads->list();
print "threads total: $thr_num\n";
if ($_->is_running())
{
sleep 1; #wait
next;
}
if ($_->is_joinable())
{
$_->join();
}
sleep 1;# wait
}
print $i,"\n";
}
这是整个代码。并且警告是 can't call method "is_running" on an undefined value at threadqueue2(1).plx.line42。 Perl 以活动线程退出。
【问题讨论】:
-
您能分享一下您收到的警告吗??
-
我已经发布了代码和警告。
-
Perl 数组从
0开始,所以也许你想做0..4而不是1..5看看你的警告是否消失。 -
是的,@xxfelixxx 是对的,在第一个代码块
@threads索引 0 元素未定义,但在第二个代码块中,您只是推入数组,因此索引 0 元素在那里未定义。在第 42 行$_->is_running()$_是 undefined,这就是您收到这些警告的原因。 -
是的,这就是问题所在。非常感谢
标签: multithreading perl variables stack