Clojure with-local-vars没有创建线程局部绑定?

时间:2013-03-31 17:09:18

标签: clojure

with-local-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
var-set

但为什么thread-local?返回false?

user=> (with-local-vars [x 1] (thread-bound? #'x))
false

1 个答案:

答案 0 :(得分:3)

因为在您的示例中,x是对包含var的变量的本地绑定。 #'x(var x)的简写,它将x解析为当前命名空间中的全局。由于with-local-vars不会影响全局 xthread-bound?会返回false

您需要使用x(而非(var x))来引用var创建的with-local-vars。例如:

(def x 1)

(with-local-vars [x 2]
  (println (thread-bound? #'x))
  (println (thread-bound? x)))

输出:

false
true

另请注意,with-local-vars不会动态重新绑定xx仅在词法上绑定到with-local-vars块中的新var。如果您调用引用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