来自clojure的勇敢和真实:
(defmacro enqueue
[q concurrent-promise-name & work]
(let [concurrent (butlast work)
serialized (last work)]
`(let [~concurrent-promise-name (promise)]
(future (deliver ~concurrent-promise-name (do ~@concurrent)))
(deref ~q)
~serialized
~concurrent-promise-name)))
(defmacro wait
"Sleep `timeout` seconds before evaluating body"
[timeout & body]
`(do (Thread/sleep ~timeout) ~@body))
(time @(-> (future (wait 200 (println "'Ello, gov'na!")))
(enqueue saying (wait 400 "Pip pip!") (println @saying))
(enqueue saying (wait 100 "Cheerio!") (println @saying))))
如果我评论(deref ~q)
行,那么只有“Cheerio!”打印出来。为什么我需要deref来获得其他副作用?
答案 0 :(得分:3)
如果您注释掉(deref ~q)
,则永远不会评估通过q
传递的代码,因此嵌套的期货不会出现。
宏扩展:
(macroexpand '(-> (future (wait 200 (println "'Ello, gov'na!")))
(enqueue saying (wait 400 "Pip pip!") (println @saying))
(enqueue saying (wait 100 "Cheerio!") (println @saying))))
;;-> ....
(clojure.pprint/pp)
(let*
[saying (clojure.core/promise)]
(clojure.core/future
(clojure.core/deliver saying (do (wait 100 "Cheerio!"))))
;; no code ended up here...
(println @saying)
saying)