Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ;; A toy implementation of cooperative multitasking with continuations in scheme/racket,
- ;; to demonstrate how it works / just for fun. By Chris H.
- ;;
- ;; note: in this scheme, if someone exits without yielding, the whole thing will get messed up
- ; For schemes other than Racket, you'll need to remove this:
- #lang Racket
- (define coop-queue '())
- ; Add a cooperative thread to the scheduling queue
- (define (schedule f) ; note: f must be a one-arg function.
- (set! coop-queue (append coop-queue (list f))))
- ; Main loop for cooperative multitasking.
- ; Schedule some threads and then call this to begin.
- ;
- ; If you wanted, you could make this loop. That would catch the case of
- ; one of the "threads" returning without yielding.
- (define (go)
- (let ((next-k (car coop-queue)))
- (set! coop-queue (cdr coop-queue))
- (sleep 0.3) ; just for fun
- (next-k #f) ; have to pass something. True is as good as anything else?
- ))
- ; y: Cooperative threads should call this when they
- ; want to yield to another thread and reschedule themselves
- ; for execution
- (define (y)
- (call-with-current-continuation
- (lambda (k)
- (set! coop-queue (append coop-queue (list k)))
- (go)
- )))
- ; an example cooperative thread.
- (define (named-count name i)
- (display name)
- (display " ")
- (display i)
- (newline)
- (y)
- (named-count name (+ i 1)))
- ; A cooperative thread to help with debugging
- (define (print-c-count)
- (display "# of functions in queue: ")
- (display (length coop-queue))
- (newline)
- (y)
- (print-c-count))
- (schedule (lambda (junk) (named-count "A" 0)))
- (schedule (lambda (junk) (named-count "B" 100)))
- (schedule (lambda (junk) (print-c-count)))
- (go)
Add Comment
Please, Sign In to add comment