Skip to content

Instantly share code, notes, and snippets.

@richo
Created May 25, 2012 00:25
Show Gist options
  • Save richo/2785057 to your computer and use it in GitHub Desktop.
Save richo/2785057 to your computer and use it in GitHub Desktop.
; Credit http://en.wikipedia.org/wiki/Continuation
;;; A naive queue for thread scheduling.
;;; It holds a list of continuations "waiting to run".
(define *queue* '())
(define (empty-queue?)
(null? *queue*))
(define (enqueue x)
(set! *queue* (append *queue* (list x))))
(define (dequeue)
(let ((x (car *queue*)))
(set! *queue* (cdr *queue*))
x))
;;; This starts a new thread running (proc).
(define (fork proc)
(call/cc
(lambda (k)
(enqueue k)
(proc))))
;;; This yields the processor to another thread, if there is one.
(define (yield)
(call/cc
(lambda (k)
(enqueue k)
((dequeue)))))
;;; This terminates the current thread, or the entire program
;;; if there are no other threads left.
(define (thread-exit)
(if (empty-queue?)
(exit)
((dequeue))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment