[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Preemption, Persistence, and Mobility

If you have continuations in your language, you can fake threads easily. 
See the PLt Scheme code below. Now you can experiment with your thread 

If you would like to read up on engines, look for the papers by Bob Hieb
and Kent Dybvig and references in there. 

If you would like to study the use of continuations in an OS so that you 
lift it back to a LL language, read Rich Draves thesis on the Mach 4
kernel, and the use of continuations in it. 

-- Matthias

(module threads mzscheme
  ; a simple thread package from call/cc

  (provide start-thread-system ; (-> Void) -> Void
           ; supply a thunk to start up the thread system (main)
           create-thread ; (-> Void) -> Void
           ; creates and enqueues a thread 

           suspend-thread ; (-> Void)
           ; suspend current thread, enqueue the suspension, run next in queue
  (require queue)

  (define (start-thread-system th)
     (lambda (s)
       (set! stop (lambda () (s (void))))
       (create-thread th)
  (define (create-thread th) 
    (enq (lambda () (th) (dispatch) (stop))))
  (define (suspend-thread)
     (lambda (k)
       (enq (lambda () (k (void))))
  ; ---------------------------------------------------------------------------
  ; auxiliary state and functions

  ; -> Void
  ; run the next thread on queue, if available 
  (define (dispatch)
    (unless (empty?) (((deq)))))

  ; stop : continuation 
  ; the continuation of the starter thread 
  (define stop void))

a tester: 

(module example mzscheme 
  (require threads)
  (define (looping x i)
    (letrec ([loop 
              (lambda (i)
                (printf "in ~s[~s]~n" x i)
                (unless (= i 0)
                  (loop (- i 1))))])
      (lambda () (loop i))))

   (lambda ()
     (create-thread (looping 'a 2))
     (create-thread (looping 'b 4)))))

the cheap queue module: 
(module queue mzscheme 
  ; a "cheap" queue implementation 
  (provide enq deq empty?)
  (define the-Q '())
  (define (empty?) (null? the-Q))
  (define (enq x) (set! the-Q (append! the-Q (list x))))
  (define (deq) (begin0 (car the-Q)  (set! the-Q (cdr the-Q)))))