为什么clojure未来会阻塞主线程? [英] Why does a clojure future block the main thread?

查看:120
本文介绍了为什么clojure未来会阻塞主线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个微不足道的项目,其中 -main 包含未来:

 (def f(future 42))

(defn -main [& args]
(println @f))
/ pre>

当我运行 lein run 时,它输出 42 但不返回。



我不明白为什么它不会返回?



get lein run 返回?

解决方案

您的问题真的有两个:


  1. 为什么lein不会返回?

lein挂起,因为支持Clojure futures的线程池不使用守护线程,明确关闭它。如果您将代码更改为以下代码,它应该可以正常工作:

 (def f(future 42))

(defn -main [& args]
(println @f)
(shutdown-agents))




  1. 期货阻止主线程

当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 prints 42 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:

  1. 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))

  1. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆