Skip to content

Instantly share code, notes, and snippets.

@QuantumGhost
Forked from yinwang0/chez-future.ss
Created August 31, 2019 08:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save QuantumGhost/b1a3729c2cdfa1dacb486c56310908e2 to your computer and use it in GitHub Desktop.
Save QuantumGhost/b1a3729c2cdfa1dacb486c56310908e2 to your computer and use it in GitHub Desktop.
experimental implementation of future with Chez Scheme threads
(define-record fitem (result ready mutex cond))
(define future
(lambda (thunk)
(let ([item (make-fitem #f #f (make-mutex) (make-condition))])
(fork-thread
(lambda ()
(let ([result (thunk)])
(with-mutex (fitem-mutex item)
(set-fitem-result! item result)
(set-fitem-ready! item #t)
(condition-broadcast (fitem-cond item))))))
item)))
(define touch
(lambda (item)
(let ([mutex (fitem-mutex item)])
(with-mutex mutex
(let loop ()
(when (not (fitem-ready item))
(condition-wait (fitem-cond item) mutex)
(loop)))
(fitem-result item)))))
(define futures
(lambda (n thunk)
(cond
[(= n 0) '()]
[else
(let ([f (future thunk)])
(cons f (futures (- n 1) thunk)))])))
(define run
(lambda (n thunk)
(for-each touch (futures n thunk))))
(define fib-it
(lambda (n)
(define iter
(lambda (a b n)
(cond
[(= n 0) b]
[else
(iter (+ a b) a (- n 1))])))
(iter 1 0 n)))
(define fib-test
(lambda () (< 1 (fib-it 1000000))))
(time (fib-test))
1750 collections
18.410461000s elapsed cpu time, including 0.111755000s collecting
18.502651000s elapsed real time, including 0.115357000s collecting
43407534256 bytes allocated, including 43373090944 bytes reclaimed
(time (run 4 fib-test))
1937 collections
88.858037000s elapsed cpu time, including 0.416044000s collecting
26.084823000s elapsed real time, including 0.421594000s collecting
173718154128 bytes allocated, including 173714549616 bytes reclaimed
Chez Scheme's memory management is parallel. CPU usage ~370%.
(time (fib-test))
cpu time: 14606 real time: 14646 gc time: 1133
(time (run 4 fib-test))
cpu time: 57944 real time: 58022 gc time: 4840
Racket's memory management is not parallel. CPU usage is 100%.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment