Guest User

Untitled

a guest
Dec 17th, 2018
187
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scheme 1.70 KB | None | 0 0
  1. ;; A toy implementation of cooperative multitasking with continuations in scheme/racket,
  2. ;; to demonstrate how it works / just for fun. By Chris H.
  3. ;;
  4. ;; note: in this scheme, if someone exits without yielding, the whole thing will get messed up
  5.  
  6. ; For schemes other than Racket, you'll need to remove this:
  7. #lang Racket
  8.  
  9. (define coop-queue '())
  10.  
  11. ; Add a cooperative thread to the scheduling queue
  12. (define (schedule f) ; note: f must be a one-arg function.
  13.   (set! coop-queue (append coop-queue (list f))))
  14.  
  15. ; Main loop for cooperative multitasking.
  16. ; Schedule some threads and then call this to begin.
  17. ;
  18. ; If you wanted, you could make this loop. That would catch the case of
  19. ; one of the "threads" returning without yielding.
  20. (define (go)
  21.   (let ((next-k (car coop-queue)))
  22.        (set! coop-queue (cdr coop-queue))
  23.        (sleep 0.3) ; just for fun
  24.        (next-k #f) ; have to pass something. True is as good as anything else?
  25.        ))
  26.  
  27. ; y: Cooperative threads should call this when they
  28. ; want to yield to another thread and reschedule themselves
  29. ; for execution
  30. (define (y)
  31.   (call-with-current-continuation
  32.    (lambda (k)
  33.      (set! coop-queue (append coop-queue (list k)))
  34.      (go)
  35.      )))
  36.  
  37. ; an example cooperative thread.
  38. (define (named-count name i)
  39.   (display name)
  40.   (display " ")
  41.   (display i)
  42.   (newline)
  43.   (y)
  44.   (named-count name (+ i 1)))
  45.  
  46. ; A cooperative thread to help with debugging
  47. (define (print-c-count)
  48.   (display "# of functions in queue: ")
  49.   (display (length coop-queue))
  50.   (newline)
  51.   (y)
  52.   (print-c-count))
  53.  
  54. (schedule (lambda (junk) (named-count "A" 0)))
  55. (schedule (lambda (junk) (named-count "B" 100)))
  56. (schedule (lambda (junk) (print-c-count)))
  57.  
  58. (go)
Add Comment
Please, Sign In to add comment