Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 make this print out as intended?

(dotimes [i 5]                                                                                                                                        
  (.start                                                                                                                                             
   (Thread.                                                                                                                                           
    (fn []                                                                                                                                             
      (Thread/sleep (rand 500))                                                                                                                       
      (println (format "Finished %d on %s" i (Thread/currentThread)))))))
;=> nil

This works fine, however:

(println (format "Finished 1 on %s" (Thread/currentThread)))
;=> Finished 1 on Thread[nREPL-worker-18,5,main]
----------- mini-buffer -----------------
nil
like image 651
kurofune Avatar asked Nov 04 '14 20:11

kurofune


1 Answers

The behavior of println is to use a dynamically bound var called *out* as its output stream. emacs dynamically binds *out* to go to the repl buffer for code evaluated in the repl buffer, but if you create a thread, that thread's *out* gets the root binding of *out*, which in the case of cider will not be the repl buffer.

If you started the repl using cider-jack-in, when you look at you buffer list there should be a buffer with a name like *nrepl-server* which contains the output of the root *out* binding. Here is the contents of mine after running your code:

nREPL server started on port 52034 on host 127.0.0.1 - nrepl://127.0.0.1:52034
Finished 1 on Thread[Thread-9,5,main]
Finished 0 on Thread[Thread-8,5,main]
Finished 2 on Thread[Thread-10,5,main]
Finished 3 on Thread[Thread-11,5,main]
Finished 4 on Thread[Thread-12,5,main]

If you did not use cider-jack-in, the output will print to the terminal where you started the nrepl process.

like image 136
noisesmith Avatar answered Sep 28 '22 03:09

noisesmith