var与运动常量的原子

Don*_*Don 8 clojure

基于命令行输入,我需要设置一些运行时常量,许多下游函数将使用这些常量.这些函数中的代码可以在其他线程中执行,因此我不考虑"声明var和使用绑定宏"组合.使用var(使用alter-var-root)与使用原子相比有什么优缺点?那是,

(declare *dry-run*) ; one of my constants

(defn -main [& args]
   ; fetch command line option
   ;(cli args ...)
   (alter-var-root #'*dry-run* (constantly ...))
   (do-stuff-in-thread-pool))
Run Code Online (Sandbox Code Playgroud)

(def *dry-run* (atom true))   

(defn -main [& args]
   ; fetch command line option
   ;(cli args ...)
   (reset! *dry-run* ...)
   (do-stuff-in-thread-pool))
Run Code Online (Sandbox Code Playgroud)

如果除了这两个之外还有其他选择我应该考虑,很想知道.

另外,理想情况下我宁愿不向原子提供初始值因为我想在其他地方设置默认值(使用cli调用),但我可以忍受它,特别是如果使用原子提供了与替代品相比的优势( S).

ama*_*loy 6

一次写入值正是Promises设计用于的用例:

(def dry-run (promise))

(defn -main []
  (deliver dry-run true))

(defn whatever [f]
  (if @dry-run
    ...))
Run Code Online (Sandbox Code Playgroud)