Article View: comp.sw.components
Article #235co-routines
From: Ted Dunning
Date: Fri, 06 Oct 1989 20:21
Date: Fri, 06 Oct 1989 20:21
50 lines
2020 bytes
2020 bytes
i recently asked about the use of call-with-continuation as a
mechanism for building co-routines (and similarly multi-tasking).
since i really was curious about how to do it, i went ahead and
implemented a simple set of coroutine support routines using
call-with-continuation.
here is the resulting code (call/cc is an abbreviation for
call-with-continuation), if you are curious about the definition of
call-with-continuation, send me email.
; this is just call/cc with a little trap for the fall through
(define (new-proc f)
(call/cc (lambda (k) (f k) (error "process returned"))))
; this is just call/cc, except that invalid continuations are avoided
; and the fall through value is changed to nil
(define (switch-to proc)
(if (continuation? proc)
(call/cc (lambda (k) (proc k) (error "process returned")))))
(define (end-proc other)
(if (continuation? other) (other nil)))
; one co-routine... prints a's
(define (proca other)
(write 'a1)
(set! other (switch-to other))
(write 'a2)
(set! other (switch-to other))
(end-proc other))
; the initial thread. starts proca and prints b's
(let ((other (new-proc proca)))
(write 'b1)
(set! other (switch-to other))
(write 'b2)
(set! other (switch-to other))
(write 'b3)
(set! other (switch-to other))
(write 'b4)
(set! other (switch-to other))
(newline))
--
ted@nmsu.edu +---------+
| In this |
| style |
|__10/6___|
Technical Details
Message-ID:
<TED.89Oct6142118@kythera.nmsu.edu>Path:
arc1-ca.pugleaf.net!utzoo!attcan!uunet!cs.utexas.edu!wuarchive!gem.mps.ohio-state.edu!uakari.primate.wisc.edu!aplcen!unmvax!pprg.unm.edu!topgun.dspo.gov!lanl!opus!tedShow Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!utzoo!attcan!uunet!cs.utexas.edu!wuarchive!gem.mps.ohio-state.edu!uakari.primate.wisc.edu!aplcen!unmvax!pprg.unm.edu!topgun.dspo.gov!lanl!opus!ted From: ted@nmsu.edu (Ted Dunning) Newsgroups: comp.sw.components Subject: co-routines Message-ID: <TED.89Oct6142118@kythera.nmsu.edu> Date: 6 Oct 89 20:21:18 GMT Sender: news@nmsu.edu Distribution: comp Organization: NMSU Computer Science Lines: 50