Hatena::ブログ(Diary)

satoru.netの自由帳 このページをアンテナに追加 RSSフィード

180114Sunday

並列処理 Parallel::ForkManager @ perl

  • 時間のかかる処理を{}で括って$pm->start and next;と$pm->finish;で待機させる
  • count1は10秒で終わる、count2は5秒で終わる処理を並列処理するサンプル
#!/usr/bin/perl

use Parallel::ForkManager;

my $pm = Parallel::ForkManager->new(2);

## 処理1
{
	$pm->start and next;
	my $count1 = 0;
	while(1){
		if($count1++ == 10){
			print "count1 finish!\n";
			last;
		}
		print "count1 $count1\n";
		sleep 1;
	}
	$pm->finish;
}

## 処理2
{
	$pm->start and next;
	my $count2 = 0;
	while(1){
		if($count2++ == 5){
			print "count2 finish!\n";
			last;
		}

		print "count2 $count2\n";
		sleep 1;
	}
	$pm->finish;
}

$pm->wait_all_children;

print "ALL FINISH $count1 $count2\n";

結果

count1 1
count2 1
count1 2
count2 2
count1 3
count2 3
count1 4
count2 4
count1 5
count2 5
count1 6
count2 finish!
count1 7
count1 8
count1 9
count1 10
count1 finish!
ALL FINISH

©satoru.net
Mail Twitter