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.
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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With