[comp.sw.components] co-routines

ted@nmsu.edu (Ted Dunning) (10/07/89)

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___|