Skip to content

Instantly share code, notes, and snippets.

@tonyg
Last active December 18, 2015 22:59
Show Gist options
  • Save tonyg/5858226 to your computer and use it in GitHub Desktop.
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>)
#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