Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure's thread does not show results in Emacs clojure-repl mode

I have this Clojure code that starts and executes a function.

(import [java.lang Thread])
(defn with-new-thread [f]
  (.start (Thread. f)))
(with-new-thread (fn [] (print "hi")))

However, when I run it in emacs in slime-repl mode (executed with cider-jack-in, there is nothing printed out, but nil returned.

enter image description here

With lein real, I got the expected output.

user=> (import [java.lang Thread])
java.lang.Thread
user=> (defn with-new-thread [f] (.start (Thread. f)))
#'user/with-new-thread
user=> (with-new-thread (fn [] (print "hello\n")))
hello
nil

What might be wrong?

like image 528
prosseek Avatar asked Dec 15 '14 22:12

prosseek


1 Answers

This happens because the main thread in CIDER/Emacs binds the REPL output buffer to the *out* dynamic var. This is why you can see things in emacs.

However when you start a new thread, that binding doesn't exist. Fixing is simple enough - first create a function which will capture the current binding:

(def  repl-out *out*)
(defn prn-to-repl [& args]
  (binding [*out* repl-out]
    (apply prn args)))

Now, whenever you want to print from a different thread, use:

(prn-to-repl "hello")

And that's it. Hope this helps.

like image 77
leonardoborges Avatar answered Nov 09 '22 03:11

leonardoborges