--- cvsroot/Coro/README 2009/05/29 07:01:18 1.23 +++ cvsroot/Coro/README 2009/06/23 23:40:06 1.24 @@ -3,8 +3,8 @@ SYNOPSIS use Coro; - - async { + + async { # some asynchronous thread of execution print "2\n"; cede; # yield back to main @@ -14,13 +14,13 @@ cede; # yield to coro print "3\n"; cede; # and again - - # use locking + + # use locking use Coro::Semaphore; my $lock = new Coro::Semaphore; my $locked; - - $lock->down; + + $lock->down; $locked = 1; $lock->up; @@ -240,9 +240,9 @@ scheme does, and are useful when you want to localise some resource to a specific coro. - They slow down coro switching considerably for coros that use them - (But coro switching is still reasonably fast if the handlers are - fast). + They slow down thread switching considerably for coros that use them + (about 40% for a BLOCK with a single assignment, so thread switching + is still reasonably fast if the handlers are fast). These functions are best understood by an example: The following function will change the current timezone to @@ -276,6 +276,36 @@ current working directory etc.) to a block, despite the existance of other coros. + Another interesting example implements time-sliced multitasking + using interval timers (this could obviously be optimised, but does + the job): + + # "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 () { } + }; + killall Kills/terminates/cancels all coros except the currently running one.