Concurrency and Parallelism
Continuations (Module 26) also let you implement green threads entirely in Scheme.
;; SRFI-18 threads (CHICKEN, Gambit, Guile with SRFI-18, Gauche)
(import (srfi 18))
(define counter 0)
(define m (make-mutex))
(define (worker)
(do ((i 0 (+ i 1))) ((= i 1000))
(mutex-lock! m)
(set! counter (+ counter 1))
(mutex-unlock! m)))
(define threads (map (lambda (i) (make-thread worker)) '(1 2 3 4)))
(for-each thread-start! threads)
(for-each thread-join! threads)
counter ; 4000
;; Guile: native threads and futures
;; (use-modules (ice-9 threads) (ice-9 futures))
;; (call-with-new-thread (lambda () ...))
;; (define f (future (expensive-computation))) (touch f)
;; (par-map square (iota 100))
;; Guile fibers: lightweight CSP-style concurrency
;; (use-modules (fibers) (fibers channels))
;; (run-fibers
;; (lambda ()
;; (let ((ch (make-channel)))
;; (spawn-fiber (lambda () (put-message ch "hello from a fiber")))
;; (get-message ch))))
;; Chez: fork-thread, make-mutex, with-mutex, make-condition, condition-wait
;; Racket: thread, channels, futures (parallel), places (parallel, message passing)
;; Gambit/Gerbil: lightweight threads and actors