Last active
December 9, 2022 10:10
-
-
Save tfidfwastaken/dbcd525e03b7fb1561342a80f54371a0 to your computer and use it in GitHub Desktop.
Back-of-the-envelope cooperative threading library in Racket
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 | |
;;; 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