Skip to content

Instantly share code, notes, and snippets.

@tfidfwastaken
Last active December 9, 2022 10:10
Show Gist options
  • Save tfidfwastaken/dbcd525e03b7fb1561342a80f54371a0 to your computer and use it in GitHub Desktop.
Save tfidfwastaken/dbcd525e03b7fb1561342a80f54371a0 to your computer and use it in GitHub Desktop.
Back-of-the-envelope cooperative threading library in Racket
#lang racket
;;; adapted from: https://youtu.be/BAMtstt3Jp8?t=1466
(define threads '())
(define (extend lst item)
(append lst (list item)))
(define (spawn func)
(set! threads
(extend threads (λ ()
(abort-current-continuation
(default-continuation-prompt-tag)
(func))))))
(define (switch)
(unless (empty? threads)
(define next (first threads))
(set! threads (rest threads))
(next)))
(define (yield)
(let/cc k
(spawn k)
(switch)))
;; Example usage
(define (looper id n)
(for ([i (in-range n)])
(printf "[~a ~a] " i id)
(yield))
(switch))
(spawn (λ () (looper 'a 5)))
(looper 'b 7)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment