Coro とは結局なんだったのか
Coro は first class の co-routine を実装しようとおもって開発してたら、「あれ、これ co-operative thread にできるのでは?」とおもいはじめたわけなのであり、そうしてみたということなのであった。
Coro は co-operative thread なわけであるが、以下のようにすると、時間ごとにスレッドをスイッチできるわけなのであり。一定時間ごとに cede; してるということなのである。CPU インテンシブな処理の最中で cede 書くのが面倒な場合にはこれが有用なのだろうとおもうのである(see Coro.pm)。
# "timeslice" the given block sub timeslice(&) { use Time::HiRes (); Coro::on_enter { # on entering the thread, we set an VTALRM handler to cede $SIG{VTALRM} = sub { cede }; # and then start the interval timer Time::HiRes::setitimer &Time::HiRes::ITIMER_VIRTUAL, 0.01, 0.01; }; Coro::on_leave { # on leaving the thread, we stop the interval timer again Time::HiRes::setitimer &Time::HiRes::ITIMER_VIRTUAL, 0, 0; }; &{+shift}; } # use like this: timeslice { # The following is an endless loop that would normally # monopolise the process. Since it runs in a timesliced # environment, it will regularly cede to other threads. while () { } };
my や local で定義された変数は thread switch の際に復帰されるわけなのであり、OOP なり local なりを駆使して書かれたコードにおいては、それほど問題が発生しないのではないか。
そんな話だったとおもう。