Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/78.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用本地变量的Clojure不创建线程本地绑定?_Clojure - Fatal编程技术网

使用本地变量的Clojure不创建线程本地绑定?

使用本地变量的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

在带有本地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
但是为什么
线程本地?
返回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