Skip to content

Instantly share code, notes, and snippets.

@tani
Created May 22, 2017 13:41
Show Gist options
  • Save tani/0f285ee1cbd053f066e32a8c2eb4a994 to your computer and use it in GitHub Desktop.
Save tani/0f285ee1cbd053f066e32a8c2eb4a994 to your computer and use it in GitHub Desktop.
Green Threads
(import (scheme base)
(scheme write)
(srfi 1)
(gauche partcont))
(define-syntax green-threads
(syntax-rules ()
((_ (yield) a)
(reset a (call/pc yield)))
((_ (yield) a b ...)
(reset a (call/pc yield) (green-threads (yield) b ...)))))
(define-syntax thread
(syntax-rules ()
((_ (args ...) body ...)
(lambda (args ...)
(reset
(shift yield
(green-threads (yield) body ...)))))))
(define (join . threads)
(if (not (null? threads))
(let ((fn (lambda (co) (co))))
(apply join (filter procedure? (map fn threads))))))
(define (p msg) (display msg) (newline))
(define foo
(thread ()
(p "foo 1")
(p "foo 2")
(p "foo 3")
(p "foo 4")
(p "foo 5")))
(define bar
(thread ()
(p "bar 1")
(p "bar 2")
(p "bar 3")
(p "bar 4")
(p "bar 5")))
(define bazz
(thread ()
(p "bazz 1")
(p "bazz 2")
(p "bazz 3")
(p "bazz 4")
(p "bazz 5")))
(join foo bar bazz)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment