http://d.hatena.ne.jp/tokuhirom/20090710/1247196134 ãã® Coro ã®ä¾ã Go ã§ãã£ã¦ã¿ã¾ãã
ã¾ãç¹å®æ° (ããã§ã¯ 3) ã® worker thread ãç«ã¡ä¸ãã¦ããã¦ãããã«ã¡ãã»ã¼ã¸ãéã£ã¦ä»äºãããã¢ãã«ãã¡ãã»ã¼ã¸ã®ããã¨ãã« Coro::Channel ã使ãã¾ãã
use Coro; use Coro::Channel; use Coro::Timer; my $ch = Coro::Channel->new; sub worker { while (1) { my $url = $ch->get; printf("worker(%d): %s\n", $_[0], $url); Coro::Timer::sleep(1); } } my @coros = ( async { worker(1) }, async { worker(2) }, async { worker(3) }, ); for my $i ( 0 .. 9 ) { $ch->put( sprintf("http://www%d.example.com/", $i) ); } $_->join for @coros;
Go ã§æ¸ãã¨ãããªããã»ã¨ãã©åãã§ãã!
package main import "fmt" import "time" var ch = make(chan string); func Worker(num int) { for { // ç¡éã«ã¼ãã㦠channel ããã®å ¥åãå¾ ã¡åãã url := <- ch; fmt.Printf("worker(%d): %s\n", num, url); time.Sleep(int64(1) * 1e9); } } func main() { go Worker(1); go Worker(2); go Worker(3); for i := 0; i < 10; i++ { ch <- fmt.Sprintf("http://www%d.example.com/", i); } for { time.Sleep(int64(1) * 1e9) } }
Go 㧠main() ã®æå¾ãloop ã㦠Sleep ãã¦ããã®ã¯ãããããªã㨠Worker ã®å®è¡ãå¾ ããªãã§çµäºãã¦ãã¾ãããã$coro->join ã«ç¸å½ããã®ã¯ã©ãããã°ããã®ããªã
次ã«ãã¨ãããã worker thread ãç«ã¡ä¸ãã¾ãã£ã¦ããã¦ãã»ããã©ã§åæå®è¡æ°ãå¶å¾¡ããã¢ãã«ãCoro::Semaphore ã使ãã¾ãã
use Coro; use Coro::Timer; use Coro::Semaphore; my $sem = Coro::Semaphore->new(3); sub worker { my ($n, $url) = @_; my $guard = $sem->guard; printf("worker(%d): %s\n", $n, $url); Coro::Timer::sleep(1); } my @coros; for my $i ( 0 .. 9 ) { my $url = sprintf("http://www%d.exmaple.com/", $i); push @coros, async { worker($i, $url) }; } $_->join for @coros;
Go ã§ã¯ãmake(chan TYPE, X) ã¨ãã㨠X åã®ã¡ãã»ã¼ã¸ããå ¥ããªã (ãã以ä¸å ¥ãããã¨ããã¨ãããã¯ãã) channel ãä½ããã®ã§ãããã»ããã©ã®ä»£ããã«ãªããåè http://golang.org/doc/effective_go.html#channels
ããããCoro ã§æ¸ããã®ã¨ã»ã¨ãã©åãæ§é ã®ã³ã¼ãã«ãªãã¾ãã
package main import "fmt" import "time" var sem = make(chan int, 3); func Worker(n int, url string) { sem <- 1; // ã»ããã©ã«å¤ãã»ãã(ã§ããªããã°block) fmt.Printf("worker(%d): %s\n", n, url); time.Sleep( int64(1) * 1e9 ); <-sem; // å®äºããã®ã§æ¶ã } func main() { for i := 0; i < 10; i++ { url := fmt.Sprintf("http://www%d.exmaple.com/", i); go Worker(i, url); } for { time.Sleep( int64(1) * 1e9 ) } }
çµè«ãGoroutine 㨠Coro ã¯ããä¼¼ã¦ããã
# ã¯ã¦ãªè¨æ³ã®ã·ã³ã¿ãã¯ã¹ãã¤ã©ã¤ããæ©ã .go ã«å¯¾å¿ããªãããªãâ¦â¦