【问题标题】:Clojure with-local-vars not creating thread-local bind?Clojure with-local-vars 不创建线程本地绑定?
【发布时间】:2013-03-31 17:09:18
【问题描述】:

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? 返回假?

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

【问题讨论】:

    标签: clojure


    【解决方案1】:

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

    你需要使用x(不是(var x))来引用with-local-vars创建的var。例如:

    (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 块中的新变量。如果你调用一个引用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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-10
      • 1970-01-01
      • 2014-06-28
      • 2011-11-15
      • 2017-10-17
      相关资源
      最近更新 更多