gpt4 book ai didi

concurrency - 没有 deref 就无法实现副作用

转载 作者:行者123 更新时间:2023-12-01 02:09:27 26 4
gpt4 key购买 nike

来自 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 来获得其他副作用?

最佳答案

如果您注释掉 (deref ~q) , 代码通过 q永远不会被评估,所以嵌套的 future 不会存在。

宏展开:

(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)

关于concurrency - 没有 deref 就无法实现副作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30383222/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com