c11cc c11cc - 15 days ago 4
Perl Question

Are these two code different

foreach $thr (1..5)
{
$threads[$thr]=threads->create("worker");
}


and

foreach (1..5)
{
push @threads,threads->create("worker");
}


the latter works well, well the former gives warning.

#!/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";
}


this is the whole code. and the warning is can't call method "is_running" on an undefined value at threadqueue2(1).plx.line42. Perl exited with active threads.

Answer

No. You will end up with different data structures. As you can see from this simplified version of your code.

#!/usr/bin/perl

use strict;
use warnings;
use 5.010;

use Data::Dumper;

my @threads;

foreach my $thr (1 .. 5) {
  $threads[$thr] = 'A Thread';
}

say Dumper \@threads;

@threads = ();

foreach (1 .. 5) {
  push @threads, 'A Thread';
}

say Dumper \@threads;

The output is:

$VAR1 = [
          undef,
          'A Thread',
          'A Thread',
          'A Thread',
          'A Thread',
          'A Thread'
        ];

$VAR1 = [
          'A Thread',
          'A Thread',
          'A Thread',
          'A Thread',
          'A Thread'
        ];

In your first example, you begin populating the array at element 1, so the first element (which has an index of 0) contains undef.