Last active
December 18, 2015 22:59
-
-
Save tonyg/5858226 to your computer and use it in GitHub Desktop.
From zero to cooperative threads in 15 lines of Racket code (after <http://www.haskellforall.com/2013/06/from-zero-to-cooperative-threads-in-33.html>)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#lang racket/base | |
(require data/queue) | |
(provide fork yield done run-threads) | |
(define current-runqueue (make-parameter #f)) | |
(define (fork thunk) | |
(enqueue! (current-runqueue) (lambda () (thunk) (done)))) | |
(define (yield) | |
(call/cc (lambda (cc) | |
(enqueue! (current-runqueue) (lambda () (cc (void)))) | |
(done)))) | |
(define (done) ((dequeue! (current-runqueue)))) | |
(define (run-threads initial-thunk) | |
(parameterize ((current-runqueue (make-queue))) | |
(initial-thunk) | |
(let run-to-completion () | |
(when (not (queue-empty? (current-runqueue))) | |
(yield) | |
(run-to-completion))))) | |
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; | |
(module+ main | |
(define (t1) | |
(for ((i 10)) | |
(printf "~a\n" (+ i 1)) | |
(yield))) | |
(define (t2) | |
(for ((i 3)) | |
(printf "Hello\n") | |
(yield))) | |
(run-threads (lambda () | |
(printf "Forking thread #1\n") | |
(fork t1) | |
(printf "Forking thread #2\n") | |
(fork t2)))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment