为什么clojure未来会阻塞主线程? [英] Why does a clojure future block the main thread?
问题描述
我有一个微不足道的项目,其中 -main
包含未来:
(def f(future 42))
/ pre>
(defn -main [& args]
(println @f))
当我运行
lein run
时,它输出42
但不返回。
我不明白为什么它不会返回?
get
lein run
返回?解决方案您的问题真的有两个:
- 为什么lein不会返回?
lein挂起,因为支持Clojure futures的线程池不使用守护线程,明确关闭它。如果您将代码更改为以下代码,它应该可以正常工作:
(def f(future 42))
(defn -main [& args]
(println @f)
(shutdown-agents))
- 期货阻止主线程
当derefing
f
如果未来不存在,线(println @f)
完成了它的工作。
这是Clojure期货的限制,可以使用 core.async 或 RxClojure 。我也一直在开发Clojure期货的替代实现,我计划很快开源并解决这些问题。
I have a trivial lein project where
-main
contains a future:(def f (future 42)) (defn -main [& args] (println @f))
When I run
lein run
it prints42
but does not return.I don't understand why it does not return ?
How do I get
lein run
to return ?解决方案Your question is really twofold:
- Why does lein not return?
lein hangs because the thread pool which backs Clojure futures does not use daemon threads so you have to explicitly shut it down. If you change your code to the following, it should work:
(def f (future 42)) (defn -main [& args] (println @f) (shutdown-agents))
- Futures block the main thread
The line
(println @f)
can potentially block the main thread when "derefing"f
if the future hasn't finished its job yet.This is a limitation of Clojure futures that can be addressed using core.async or RxClojure. I've also been working on an alternative implementation of futures for Clojure that I plan to open source very soon and addresses these issues.
这篇关于为什么clojure未来会阻塞主线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!