Coroutines

Andreas Gruenbacher gruenbacher-lists@geoinfo.tuwien.ac.at
Tue, 20 Mar 2001 18:07:25 +0100 (CET)


On Mon, 19 Mar 2001, Hannah Schroeter wrote:

> Hello!
>
> On Mon, Mar 19, 2001 at 06:43:55PM +0100, Andreas Gruenbacher wrote:
>
> > On Mon, 19 Mar 2001, Simon Peyton-Jones wrote:
> >
> > > Lazy evaluation *is* coroutines, in a way.
> >
> > What I had in mind was something like the following (pseudocode), which
> > could easily be implemented on top of coroutines:
> >
> > class Channel c t where
> > 	send    :: t -> c -> IO ()
> > 	receive ::      c -> IO t
> >
> > sender :: Int -> Channel -> ...
> > sender n receiver = do send n receiver
> >                        return (sender (n+1) receiver)
> >
> > receiver :: Channel -> ...
> > receiver sender = do i <- receive sender
> >                      return (receiver sender)
> >
> > c :: Channel Int
> > c = ...
> >
> > main = run_them [ sender 1 c, receiver c ]
>
> Now, you can do this:
>
> sender :: Int -> [Int]
> sender n = n:(sender (n+1))
>
> receiver :: [Int] -> ()
> receiver (x:xs) = receiver xs
>
> main =
> 	let
> 		sent_stuff = sender 1
> 		receiver_result = receiver sent_stuff
> 	in
> 		receiver_result `seq` return ()
>
> I.e. lazy lists work like coroutine channels often enough.

I see your point, and I must admit that this approach has its charm. It's
not what I had in mind, though. Simon's MVars (in the Awkward Squad)
come pretty close, but they're still not the sort of (cooperative)
multitasking that I'm thinking of. I'm not looking for a process or thread
model of concurrency. That's too expensive for simulations due to the
frequency of task switches. (And thanks Rita, for the Eden reference.
That's comparable to Concurrent Haskell.)

The sort of lazy evaluation employed in your solution is in a way similar
to coroutines, with the following restrictions (correct me if I'm wrong):

* It is not possible to implement cyclic communication.
* It is not possible to implement processes with multiple asynchronous
  output channels.

I really would like to preserve the elegance of simulations in Simula, but
with all the advantages Haskell offers. I believe that in current Haskell
implementations all the components needed for "proper" coroutines are more
or less there (because lazy evaluation is pretty close).

Any more ideas?

Thanks,
--Andreas.