如何在for循环中运行Perl线程

时间:2013-09-15 13:11:20

标签: perl

我有一个多线程主Perl脚本。我想要做的是每个线程将有3个命令运行,一旦整个线程完成,我希望我的脚本再次触发相同的线程,基本上在循环中,任何人都可以让我知道如何做到这一点

这是我的 perl代码段

my @finalOneClickarray= grep(/\S/, @oneclickConcurrentbackup); #----Removing the empty content from the array---#   

#---Making Concurrent OneClick backup commands using threads------#
my @threads;

#-----performing the CHO loops as given by user-------#
foreach (@finalOneClickarray) {
    push @threads, threads->new(\&concurrentBackupCommandsRead, $_);
}

foreach (@threads) {
    $_->join();
}

concurrentBackupCommandsRead 是执行命令的方法。

更新的perl代码: -

use threads;
use threads::shared;
my @arr = (1,2,3,4);
my $outnumber :shared =4;


print "\n variable outside thread that is in main program $outnumber\n";
my @threads;


for($i=0;$i<=3; $i++)
{
  print "\ncalling subrountine vinay for $i times\n";

  vinay();

}

sub vinay()
{
    foreach (@arr) {
       push @threads, threads->create(\&doSomething);
    }
    foreach (@threads) {
       $_->join();
    }
}

sub doSomething ()
{

 print "\n Before increment is $outnumber\n";
 my $foo = $outnumber; 
 $outnumber = $foo + 1;

print "\n After increment is $outnumber\n";

}

1 个答案:

答案 0 :(得分:1)

在第二次循环运行时,您正在尝试加入已加入的线程(因为您只添加到@threads)。这会引发错误,“线程已加入”。

清除@threads,或将其本地化为vinay(),例如

sub vinay()
{
    my @threads;
    foreach (@arr) {
       push @threads, threads->create(\&doSomething);
    }
    foreach (@threads) {
       $_->join();
    }
}