当clojure未来结束时,有没有办法得到通知?

zca*_*ate 6 clojure

有没有办法在未来设置监视器,以便在完成后触发回调?

这样的事情?

> (def a (future (Thread/sleep 1000) "Hello World!")
> (when-done a (println @a))

...waits for 1sec...
;; =>  "Hello World"
Run Code Online (Sandbox Code Playgroud)

Art*_*ldt 13

您可以启动另一个监视未来的任务,然后运行该功能.在这种情况下,我将只使用另一个未来.哪个很好地包含在一个完成函数中:

user=> (defn when-done [future-to-watch function-to-call] 
          (future (function-to-call @future-to-watch)))
user=> (def meaning-of-the-universe 
         (let [f (future (Thread/sleep 10000) 42)] 
            (when-done f #(println "future available and the answer is:" %)) 
            f))
#'user/meaning-of-the-universe

... waiting ...

user=> future available and the answer is: 42
user=> @meaning-of-the-universe
42
Run Code Online (Sandbox Code Playgroud)


小智 5

对于非常简单的情况:如果您不想阻塞并且不关心结果,只需在将来的定义中添加回调即可。

(future (a-taking-time-computation) (the-callback))
Run Code Online (Sandbox Code Playgroud)

如果您关心结果,请使用 comp 和回调

(future (the-callback (a-taking-time-computation)))
Run Code Online (Sandbox Code Playgroud)

或者

(future (-> input a-taking-time-computation callback))
Run Code Online (Sandbox Code Playgroud)

从语义上讲,java 等效代码是:

final MyCallBack callbackObj = new MyCallBack();
new Thread() {
     public void run() {
         a-taking-time-computation();
         callbackObj.call();
     }
 }.start()
Run Code Online (Sandbox Code Playgroud)

对于复杂的情况,您可能需要查看:

https://github.com/ztellman/manifold

https://github.com/clojure/core.async