【问题标题】:WITH-OUTPUT-TO-STRING with multithreading in Common LispWITH-OUTPUT-TO-STRING 与 Common Lisp 中的多线程
【发布时间】:2023-02-17 11:02:47
【问题描述】:
我想做一些具有以下意义的事情:
(with-output-to-string (*standard-output*)
(bt:join-thread
(bt:make-thread
(lambda ()
(format *standard-output* "Hello World")))))
;=> "" (actual output)
;=> "Hello World" (expected output)
在我的理解中,这是行不通的,因为在线程外被with-output-to-string动态反弹的*standard-output*不会在线程内生效。有哪些可行和可推荐的方式?
本质上,我想捕获另一个线程写入*standard-output* 的输出。
【问题讨论】:
标签:
multithreading
scope
common-lisp
dynamic-scope
【解决方案1】:
我能想到的一种方法是改变原始绑定本身:
(let ((original-stdout *standard-output*))
(with-output-to-string (stdout)
(unwind-protect
(progn
(setq *standard-output* stdout)
(bt:join-thread
(bt:make-thread
(lambda ()
(format *standard-output* "Hello World")))))
(setq *standard-output* original-stdout))))
这实现了我想要的——它返回"Hello World",即使它是从另一个线程写入*standard-output*。但我不确定是否有更好的方法来实现这一目标。