使用本地变量的Clojure不创建线程本地绑定?
在带有本地var的使用本地变量的Clojure不创建线程本地绑定?,clojure,Clojure,在带有本地var的文档中 varbinding=> symbol init-expr Executes the exprs in a context in which the symbols are bound to vars with per-thread bindings to the init-exprs. The symbols refer to the var objects themselves, and must be accessed with var-get and v
文档中
varbinding=> symbol init-expr
Executes the exprs in a context in which the symbols are bound to
vars with per-thread bindings to the init-exprs. The symbols refer
to the var objects themselves, and must be accessed with var-get and
var-set
但是为什么线程本地?
返回false
user=> (with-local-vars [x 1] (thread-bound? #'x))
false
因为在您的示例中,x
是对包含var
的变量的本地绑定#'x
是(var x)
的缩写,它将x解析为当前命名空间中的全局变量。由于使用本地变量的不会影响全局x
,线程绑定?
返回false
您需要使用x
(而不是(var x)
)来引用使用本地变量创建的var
。例如:
(def x 1)
(with-local-vars [x 2]
(println (thread-bound? #'x))
(println (thread-bound? x)))
产出:
false
true
另外,请注意,使用本地变量的不会动态地重新绑定x
x
仅在词汇上绑定到带有本地变量的块中的新变量。如果调用引用x
的函数,它将引用全局x
如果要动态重新绑定x
,则需要使用binding
并使x
动态:
(def ^:dynamic x 1)
(defn print-x []
(println x))
(with-local-vars [x 2]
(print-x)) ;; This will print 1
(binding [x 2]
(print-x)) ;; This will print 2