[plt-scheme] Implementing engines using threads

From: Jens Axel Søgaard (jensaxel at soegaard.net)
Date: Tue Apr 27 17:39:14 EDT 2004

For fun I tried implementing engines using threads. The following
almost works. When the computation performed by the engine finishes
success is called with the result of the computation. I'd like the
to see the result of success return to the caller of the engine,
but in the solution the return value of success is returned to
the work thread (which immediately thereafter ends).

(define (make-engine a-thunk)
   (lambda (ticks success failure)
     (let ([work-thread (thread (lambda () (success (a-thunk))))])
       (if (not (object-wait-multiple ticks work-thread))
             (thread-suspend work-thread)
             (letrec ([new-engine (lambda (ticks success failure)
                                    (thread-resume work-thread)
                                    (if (not (object-wait-multiple ticks work-thread))
                                          (thread-suspend work-thread)
                                          (failure new-engine))))])
               (failure new-engine)))))))

I tried this:

(define (make-engine a-thunk)
   (lambda (ticks success failure)
     (call/cc (lambda (return)
       (let ([work-thread (thread (lambda () (return (success (a-thunk)))))])

but it goes with out saying that a continuation captured in one thread
can not be reified in another.

Is there an elegant way to communicate the return value of success to
the caller of the engine?

; Example from Sitarams "Teach Your Self Scheme in a Fixnum Days":

(define printn-engine
    (lambda ()
      (let loop ((i 10))
          [(> i 0) (display i)
                   (display " ")
                   (sleep 1)
                   (loop (- i 1))]
          [else    'lift-of])))))

(define *more* #f)
(printn-engine 5 list (lambda (ne) (set! *more* ne)))
(*more* 2 list (lambda (ne) (set! *more* ne)))
(*more* 10 list (lambda (ne) (set! *more* ne)))

Jens Axel Søgaard

Posted on the users mailing list.