【perl语言】利用threads实现多线程运算

代码如下

#!/usr/bin/env perl 
use strict;
use threads;
use Thread::Semaphore;

my $trait = $ARGV[0];
my $NumOfTrait = 0;
my $thread;
my $max_cpu = 28;
my $semaphore = new Thread::Semaphore($max_cpu);
my (@line, @line, %traitDict, $i);

open REF, "taxa_".$trait.".txt";
while(<REF>){
  chomp;
  @line = split /\t/;
  $traitDict{$line[0]} = $line[1];
  $NumOfTrait ++;
}

# check num of trait <> 28
for($i=1; $i<=$NumOfTrait; $i++){
  $semaphore->down();
  $thread = threads->new(\&run_gemma, $trait, $i, $traitDict{$i});
  $thread->detach();
}
#
&waitquit();

# functions 
sub waitquit{
  my ($i);
  for($i=0;$i<$max_cpu;$i++){
    $semaphore->down();
  }
  $semaphore->up($max_cpu);
}

sub run_gemma{
  my($phe, $col, $name) = @_;
  system("bash ../02.gemma.sh Bna171_".$phe." ".$col." ".$name);
  print "[INFO] $name is done.\n";
  $semaphore->up();
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容