SICP 3.4.2 parallel-executeの実装
これ以降やるための準備です.
gauche.threadsの使い方がわからなかったのでリファレンス見ながらググって見つけたコードを理解しました.
(use gauche.threads) (define (delay time proc) (lambda () (thread-sleep! time) (proc))) (define (delay-print time name) (delay time (lambda () (print name) name)))
(let ((t1 (make-thread (delay-print 4 "First thread"))) (t2 (make-thread (delay-print 2 "Secound thread")))) (thread-start! t1) (thread-start! t2) (print "Main thread") (thread-join! t1) (thread-join! t2)) Main thread Secound thread First thread "Secound thread"
procs
にある手続きに対して全てmake-thread
してthreads
に保存.
threads
に保存したスレッドを全てスタートし,ジョインで値を取る.
スレッドをスタートしているので値を得る前に次のスレッドをスタートできるので並列に実行していることになる.
(define (parallel-execute . procs) (let ((i 0)) (let ((threads (map (lambda (proc) (set! i (+ i 1)) (make-thread proc i)) procs))) (map thread-start! threads) (map thread-join! threads))))
gosh> (parallel-execute (delay-print 4 "A") (delay-print 2 "B") (delay-print 1 "C")) C B A ("A" "B" "C")
参考