Tuesday, September 25, 2012

Perl範例 : 支援多執行緒

這是很久以前在 NCU ISL 當助理時寫的程式碼, 最近流行考古就找到這隻程式. 話說這年頭大家都玩 CUDA, OpenCL, 應該不會有人對這感興趣. 不過還是將程式碼放上來作為紀錄參考用.

程式碼(runcosmicgmrion.pl)
#!/usr/bin/perl

use threads;
use threads::shared;
use Thread;
use Switch;
use Time::localtime;

# Define floder name of data and get rootpath
my $datafloder : shared;
$datafloder = "lv2data_1";      # Data floder to run
my $rootpath : shared;
$rootpath = shift;

# Define job and nodename as shared variable
print "Begin time : ",ctime(),"\nInit job and cpu : ";
my @job : shared;
my $lastjob : shared;
my @cpu : shared;

# Get jobflodername
@job = `ls $rootpath/$datafloder`;
chop(@job);
$lastjob = $#job;

# Define nodename and cpuid(begin from 0)
@cpu = qw (Logon ve1 ve2 ve3 ve4 ve5);
#@cpu = qw (ve1 ve3 ve5);
#@cpu = qw (ve1);

my $i;

$threadnum = 0;
print "done ! \n";

while($lastjob >=0){
    my $thread0, $thread1, $thread2, $thread3, $thread4, $thread5;
    for($i = 0; $i <= $#cpu;$i++){
        if($lastjob >= 0){
            my $jobpath = $rootpath . "/" . $datafloder . "/" . $job[$lastjob];
            switch ($i) {
                case "0" { $thread0 = threads->new(\&exgmrion, $jobpath, 0); }
                case "1" { $thread1 = threads->new(\&exgmrion, $jobpath, 1); }
                case "2" { $thread2 = threads->new(\&exgmrion, $jobpath, 2); }
                case "3" { $thread3 = threads->new(\&exgmrion, $jobpath, 3); }
                case "4" { $thread4 = threads->new(\&exgmrion, $jobpath, 4); }
                case "5" { $thread5 = threads->new(\&exgmrion, $jobpath, 5); }
                else     { print "Error : can't assign job"; }
            }
            $lastjob--;
        }else{
            last;
        }
    }

    my $thnum = $i - 1;
    switch ($thnum) {
                case "0" { $_->join foreach ($thread0); }
                case "1" { $_->join foreach ($thread0, $thread1); }
                case "2" { $_->join foreach ($thread0, $thread1, $thread2); }
                case "3" { $_->join foreach ($thread0, $thread1, $thread2, $thread3); }
                case "4" { $_->join foreach ($thread0, $thread1, $thread2, $thread3, $thread4); }
                case "5" { $_->join foreach ($thread0, $thread1, $thread2, $thread3, $thread4, $thread5); }
                else     { print "Error : can't run !"; }
    }

}

print "Finished time : ",ctime(),"\n";

sub exgmrion: locked method {
    my ($expath, $cpuid) = @_;
    my $excpu = $cpu[$cpuid];
    print "Excution cosmic_gmrion in $expath on $excpu \n";
    system("rsh $excpu threadperl/t02_do/exgmrion.pl $expath $excpu");
}

No comments: