Coroでmuxtapeの情報取得をparalell化
dmakiさんの記事を参考に、つい先日書いたmuxtapeの情報取得スクリプトをCoro化してみました。
http://mt.endeworks.jp/d-6/2008/04/coroflickr.html
Coroは、Javaだとconcurrent.utilに相当するものですね。お手軽に処理をパラレル化できるので、色々と使える場面がありそうです。
#!/usr/bin/env perl use strict; use warnings; use Benchmark qw(:all); use FindBin::libs; use Coro; use Coro::AnyEvent; use Coro::LWP; use WWW::Muxtape::Scraper; use URI; use Perl6::Say; use YAML::Syck; $YAML::Syck::ImplicitUnicode = 1; my $t = timeit(1, \&main); print "main code took:",timestr($t),"\n"; sub main { say "collecting tapes ..."; my $tapes = collecting_tape_pages(); generate_tape_lists($tapes); say "Done! See muxtape.yaml ;)"; } sub collecting_tape_pages { my $muxtape = WWW::Muxtape::Scraper->new; my $tape_lists = $muxtape->top_page->scrape(); my $tapes = []; my @coros; foreach my $tape ( @{$tape_lists} ) { push @coros, async { say 'collecting tape info: ' . $tape->{tapename}; push @{$tapes}, $muxtape->tape_page->scrape( tapename => $tape->{tapename} ); say 'collected: ' . $tape->{tapename}; } } $_->join for @coros; $tapes; } sub generate_tape_lists { my $tapes = shift; DumpFile( "muxtape.yaml", $tapes ); } __END__
dmakiさんの記事にも書いてありますが、今回のCoroの使い方のポイントは、以下の2点。
use Coro; use Coro::AnyEvent; use Coro::LWP; use LPW系モジュール;
my @coros; foreach my $tape ( @array ) { push @coros, async { 'do something' } } $_->join for @coros; #処理待ち