I recently hacked a module named Coro (short for coroutines, similar
but not the same as threads or perl's faked threads). After using it to
implement fake continuations (to make damian conway happy, if he ever
finds out) I thought let's give Event a try (no, not faked this time ;)

   use Coro 0.04;
   use Coro::Event;

   my $stdin = Coro::Event->io(fd => \*STDIN, poll => 'r');

   # read one line from the filehandle. if we were doing non-blocking i/o
   # we could loop inside this function until a complete line has arrived
   sub kbdline {
      $stdin->next; # wait for & fetch next event
      my $x = <STDIN>; chomp $x; $x;
   }

   # this creates a new asynchronous coroutine
   sub keyboard : Coro {
      $| = 1;
      # loop endlessly and fetch commands
      while () {
         print "cmd> ";  my $cmd  = kbdline;
         print "data> "; my $data = kbdline;
         # maybe read more lines, depending on the command
         print "cmd<$cmd> data<$data>\n";
         print "working...";
         do_timer(after => 1); # wait a second before continuing
         print "done\n";
      }
   }

   sub finger : Coro {
      use IO::Socket::INET;
      # is there ANY way to do non-blocking connects with IO::Socket::INET?
      # I don't see how...
      my $io = new IO::Socket::INET PeerAddr => "noc.dfn.de:finger";
      print "connected, sending finger request\n";
      syswrite $io, "trouble\n";
      my $r = Coro::Event->io(fd => $io, poll => 'r');
      my $buf;
      # now assemble the return data
      $r->next while 0 != sysread $io, $buf, 8192, length $buf;
      print $buf;
   }

   Coro::Event->main;

it is difficult to get the point across using a small program - the idea
is to linearize programs, while still using the benefits of a state
machine. My ideal for perl 6 and high performance servers is to start one
real (os) thread per cpu and then use event and coroutines to distribute
work....

I still have small problems with the design (localize $_ or not? i am for
not...), but given that I thought this to be much too complicated for many
years it was surprisingly easy to implement so far... (yes, there are many
unresolved logical problems, but it's the first version... 0.05 will be
much better ;)

I hope you found this posting somewhat entertaining...

-- 
      -----==-                                             |
      ----==-- _                                           |
      ---==---(_)__  __ ____  __       Marc Lehmann      +--
      --==---/ / _ \/ // /\ \/ /       [EMAIL PROTECTED]      |e|
      -=====/_/_//_/\_,_/ /_/\_\       XX11-RIPE         --+
    The choice of a GNU generation                       |
                                                         |

Reply via email to