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

1

6

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?

Baseman answered 15/12, 2014 at 22:55 Comment(0)
P
9

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.

Pereyra answered 15/12, 2014 at 23:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.