-1
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\[email protected]\n";
#print $out "Threads ID:$tid\[email protected]\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";
}
這是整個代碼。並且警告是無法在線程隊列2(1).plx.line42上的未定義值上調用方法「is_running」。 Perl用活動線程退出。
你能否分享一下你所得到的警告? – AbhiNickz
我已發佈代碼和警告。 – c11cc
Perl數組從'0'開始,所以也許你想做'0..4'而不是'1..5',看看你的警告是否消失。 – xxfelixxx