首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Clojure with-local-vars没有创建线程本地绑定吗?

Clojure with-local-vars没有创建线程本地绑定吗?
EN

Stack Overflow用户
提问于 2013-04-01 01:09:18
回答 1查看 352关注 0票数 1

with-local-var文档中

代码语言:javascript
复制
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呢?

代码语言:javascript
复制
user=> (with-local-vars [x 1] (thread-bound? #'x))
false
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-04-01 05:07:31

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

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

代码语言:javascript
复制
(def x 1)

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

输出:

代码语言:javascript
复制
false
true

还要注意,with-local-vars不会动态地重新绑定xx仅在词法上绑定到with-local-vars块中的新var。如果调用引用x的函数,它将引用全局x

如果您想要动态重新绑定x,则需要使用binding并将x动态化:

代码语言:javascript
复制
(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
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15732102

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档