Path: katsu From: katsu@sra.CO.JP (WATANABE Katsuhiro) Message-ID: Date: 02 Jan 1998 20:41:56 GMT Organization: Software Research Associates, Inc., Japan Distribution: Newsgroups: comp.lang.scheme Subject: How to implement coroutine Followup-To: comp.lang.scheme Mime-Version: 1.0 (generated by tm-edit 7.47) Content-Type: text/plain; charset=US-ASCII I love coroutine. And Scheme, too. I wrote a code to make coroutines as following, with refering the book "Essentials of Programming Languages"[1]. (define call/cc call-with-current-continuation) (define resume '*) (define makecoroutine (lambda (body) (let ((last-continuation '())) (letrec ( (newcoroutine (lambda (value) (last-continuation value))) (localresume (lambda (cont value) (let ((value (call/cc (lambda (localcont) (begin (set! last-continuation localcont) (cont value)))))) (begin (set! resume localresume) value))))) (call/cc (lambda (exit) (begin (body (localresume exit newcoroutine)) (error "It never comes here.")))))))) (define example (lambda () (call/cc (lambda (returncont) (letrec ( (co1 (makecoroutine (lambda (initval1) (begin (display "coroutine 1 initval1:") (display initval1) (newline) (set! initval1 (resume co2 (+ 1 initval1))) (display "coroutine 1 initval1:") (display initval1) (newline) (set! initval1 (resume co2 (+ 1 initval1))) (returncont initval1) ; In this implementation of makecoroutine, ; a coroutine must not return. )))) (co2 (makecoroutine (lambda (initval2) (begin (display "coroutine 2 initval2:") (display initval2) (newline) (set! initval2 (resume co1 (+ 1 initval2))) (display "coroutine 2 initval2:") (display initval2) (newline) (resume co1 (+ 1 initval2))))))) (co1 33)))))) This code does "set!" to the variable "resume", which has global scope. As a result, (I think) the code won't work in case: (a) Within a coroutine, make and use another coroutine. (b) Use coroutines in a concurrent environment ("future"). Does anyone know how to implement coroutine that works even in case of (a) and (b) ? I don't stick to the interface of makecoroutine and example above. I will welcome any implementation which provides quivalent functionarity. I'm using MacGambit v2.2.1. [1] Daniel P. Friedman, Mitchell Wand, Chiristopher T. haynes; "Essentials of Programming Languages"; MIT Press; ISBN 0-262-06145-7 Descriptions about coroutines from p.312. -- WATANABE Katsuhiro Software Research Associates, Inc. Tokyo, Japan.