Why can't I print from background threads in Clojure Cider REPL in emacs?

前端 未结 4 897
执笔经年
执笔经年 2020-12-03 04:10

If I try to evaluate the following code in my emacs cider-repl, nil is returned, as expected, but none of the printing takes place in the repl buffer or console. How can I m

4条回答
  •  -上瘾入骨i
    2020-12-03 04:32

    *out* is the dynamic variable determining where output from println and similar functions goes. It is thread-bound to someplace that causes stuff to be sent back to emacs for display by cider; if you start a new thread, that binding is not present, and the output goes elsewhere (probably to the stdout of the nrepl server emacs/leiningen started in the background).

    You can address this in a few ways. You could capture the value of *out* from the parent thread, and then pass it along to the child thread in a closure, and rebind *out* to it:

    (let [out *out*] 
      (.start (Thread. (fn [] 
                         (binding [*out* out]
                            (println "test"))))))
    

    Or you can use a future instead of starting the thread yourself: Clojure automatically conveys relevant thread-local bindings to new threads started for a future.

提交回复
热议问题