まぁ、C++で使うことはないのでSagittariusですごくナイーブに実装してみた。ひょっとしたら使うようになるかもしれないというだけで。
(import (rnrs) (srfi :18) (clos user))
(define-class <promise> ()
  ((future :init-keyword :future)
   (thread :init-keyword :thread :accessor promise-thread)))
(define-class <future> ()
  ((promise :accessor future-promise)))
(define (make-promise proc . args)
  (let* ((thunk (lambda () (apply proc args)))
  (thread (make-thread thunk))
  (future (make <future> :thunk thunk))
  (promise (make <promise> :future future :thread thread)))
    (future-promise future promise)
    (thread-start! thread)
    promise))
(define-method get-future ((p <promise>))
  (slot-ref p 'future))
(define-method get ((f <future>))
  (let ((promise (future-promise f)))
    (thread-join! (promise-thread promise))))
(let* ((promise (make-promise (lambda args
    (thread-sleep! 1000) ;; heavy routine
    (apply + args)) 1 2 3 4))
       (future (get-future promise)))
  ;; do something 
  (print 'here)
  ;; wait
  (print "get value " (get future)))
こんな感じ?あんまり何も考えてない。値の取得が2回起きたらどうなるとか。なんかこの程度だとスレッドの薄いラッパーにしか見えないなぁ。どうするのが正しいんだ?
 
 
No comments:
Post a Comment