如何在Clojurescript中实现原子? [英] How are Atoms implemented in Clojurescript?

查看:121
本文介绍了如何在Clojurescript中实现原子?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Clojure解决并发问题我们可以使用原子来写:

  user => (def my-atom(atom 0))
#'user / my-atom

user => @ my-atom
0

user => (swap!my-atom inc)
1

user => @ my-atom
1

user => (swap!my-atom(fn [n](*(+ nn)2)))
4

我们知道(在Clojure实现中) Java原子对象的包装器



有趣的是,Atoms 在ClojureScript 中在语法级别进行复制 - 即使JavaScript运行时没有Atomic引用。



我的问题是, Atoms如何在Clojurescript中实现?它们只是一个对象Wrapper吗?



在源代码$ b中$ b https://github.com /clojure/clojurescript/blob/master/src/main/cljs/cljs/core.cljs#L4081

  (deftype Atom [state meta validator watches] 
...
IDeref
(-deref [_] state)
...)


https://github.com/clojure/clojurescript/blob/master/src/main/cljs/cljs/core.cljs#L4110

 (defn atom 
创建并返回Atom ...
。x nil nil nil))
([x& {:keys [meta validator]}](Atom。 x meta validator nil)))

检查 swap! code>和重置!您会发现:



(。-state a)new-value)



然后,转到 https://github.com/clojure/clojurescript/blob/3bb97961cbc958aeaeac506222dc7b9dcb0e9fc1/src/clj/cljs/compiler.clj #L771 set!,你会发现编译器只是发出一个赋值语句:

 (defmethod emit *:set!
[{:keys [target val env]}]
(emit-wrap env(emit target=val)) )


In Clojure to address concurrency issues we can use an atom to write:

user=> (def my-atom (atom 0))
#'user/my-atom

user=> @my-atom
0

user=> (swap! my-atom inc)
1

user=> @my-atom
1

user=> (swap! my-atom (fn [n] (* (+ n n) 2)))
4

We know that this (in the Clojure implementation) is a wrapper around the Java Atomic object.

Interestingly enough, Atoms are replicated in ClojureScript, at a Syntactic level - even though JavaScript runtimes don't have an Atomic reference.

My question is, How are Atoms implemented in Clojurescript? Are they just an object Wrapper?

解决方案

It just returns and assigns the value.

In the source https://github.com/clojure/clojurescript/blob/master/src/main/cljs/cljs/core.cljs#L4081

(deftype Atom [state meta validator watches]
  ...
  IDeref
  (-deref [_] state) 
  ...)

and https://github.com/clojure/clojurescript/blob/master/src/main/cljs/cljs/core.cljs#L4110

(defn atom
  "Creates and returns an Atom ..."
  ([x] (Atom. x nil nil nil))
  ([x & {:keys [meta validator]}] (Atom. x meta validator nil)))

check the implementation of swap! and reset! you will find out:

(set! (.-state a) new-value)

then , go to https://github.com/clojure/clojurescript/blob/3bb97961cbc958aeaeac506222dc7b9dcb0e9fc1/src/clj/cljs/compiler.clj#L771 the set!, you will find the compiler just emits an 'assignment statement':

(defmethod emit* :set!
  [{:keys [target val env]}]
  (emit-wrap env (emits target " = " val)))

这篇关于如何在Clojurescript中实现原子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆