gpt4 book ai didi

multithreading - 使用 swank/slime 理解 Clojure 中的输出

转载 作者:行者123 更新时间:2023-12-04 16:02:15 24 4
gpt4 key购买 nike

当我在 emacs 中从 Swank repl 运行 Clojure 代码时,主线程将使用 printf 将消息打印到 repl。但是,如果我运行代理或显式创建也打印的其他线程,有时输出不会显示,有时它会显示在我正在运行 Swank 的控制台窗口中。我很想知道为什么。

编辑:感谢丹尼尔在下面的回答,我现在知道其他线程没有绑定(bind)到 REPL 的输出。此代码有效,因为您从运行的地方传入 out。然而我的新问题是,这段代码现在每个线程都阻塞,所以它不是并行运行,而是一次运行每个线程,所以我需要一个更能感知线程的输出方法。

(defn sleeper-thread [out id t]
"Sleep for time T ms"
(binding [*out* out]
(printf "%d sleeping for time %d\n" id t)
(Thread/sleep t)
(printf "%d slept\n" id)))

(defn test-threads [n out]
(dotimes [x n]
(.start (Thread. (#(sleeper-thread %1 %2 %3) out x (+ 2000 (rand-int 5000)))))))

最佳答案

原因是,在其他线程 *out*不绑定(bind)到 REPL 的流。尝试这样的事情:

(let [repl-out *out*]
(defn foo []
(binding [*out* repl-out]
...)))

现在,当运行 foo来自另一个线程, *out*将绑定(bind)到您定义函数时的任何内容(即 SLIME REPL),因此打印将按预期工作。

或者,为了测试:
(defmacro future-output [& body]
`(let [out# *out*]
(future
(binding [*out* out#]
~@body))))

注意:这是未经测试的,因为我在 atm 没有工作 Clojure/SLIME,但该代码在几个月前工作。 newer Versions of Clojure 中可能存在差异(1.3 阿尔法 2):

  • code path for using vars is now much faster for the common case, and you must explicitly ask for :dynamic bindability

关于multithreading - 使用 swank/slime 理解 Clojure 中的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4532862/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com