ref-set vs commute vs alter [英] ref-set vs commute vs alter

查看:149
本文介绍了ref-set vs commute vs alter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Clojure中3种方式设置ref的值有什么区别?我已经阅读过几次关于ref-set,commute和alter的文档。我很困惑哪些在什么时候使用。

What is the difference in the 3 ways to set the value of a ref in Clojure? I've read the docs several times about ref-set, commute, and alter. I'm rather confused which ones to use at what times. Can someone provide me a short description of what the differences are and why each is needed?

推荐答案

作为一个超简单的解释如何软件事务内存系统在clojure工作;它重试事务,直到他们的每个人都通过,没有从它下面的值改变。您可以通过使用ref-changing函数来帮助它做出这个决定,它会提示交易之间的交互是否安全。

As a super simple explanation of how the Software Transactional Memory system works in clojure; it retries transactions until everyone of them gets through without having its values changed out from under it. You can help it make this decision by using ref-changing-functions that give it hints about what interactions are safe between transactions.


  • ref-set 适用于您不关心当前值的情况。 只需将其设置为 ref-set 为您节省写入(alter my-ref(fun [_] 4))只要把my-ref的值设置为4. (ref-set my-ref 4)肯定看起来好多了。

    使用 ref-set 可以设置该值。

  • ref-set is for when you don't care about the current value. Just set it to this! ref-set saves you the angst of writing something like (alter my-ref (fun [_] 4)) just to set the value of my-ref to 4. (ref-set my-ref 4) sure does look a lot better :).
    Use ref-set to simply set the value.

alter 是最常见的标准版本。使用此功能更改值。这是STM的肉。它使用您传递的函数来更改值,如果不能保证该值在事务开始时没有改变,则重试。这是非常安全的,即使在某些情况下,你不需要 安全,例如增加一个计数器。
大部分时间您可能想要使用 alter

alter is the most normal standard one. Use this function to alter the value. This is the meat of the STM. It uses the function you pass to change the value and retries if it cannot guarantee that the value was unchanged from the start of the transaction. This is very safe, even in some cases where you don't need it to be that safe, like incrementing a counter. You probably want to use alter most of the time.

commute 是alter的优化版本,当时的顺序并不重要。它没有区别谁添加哪个+1到计数器。结果是一样的。如果STM决定你的事务是否安全提交,它只有通勤操作上的冲突,没有对alter操作,那么它可以继续并提交新的值,而不必重新启动任何人。

使用 commute 可以节省偶尔的事务重试次数,但不会在正常代码中看到 code>。

commute is an optimized version of alter for those times when the order of things really does not matter. it makes no difference who added which +1 to the counter. The result is the same. If the STM is deciding if your transaction is safe to commit and it only has conflicts on commute operations and none on alter operations then it can go ahead and commit the new values without having to restart anyone. This can save the occasional transaction retry though you're not going to see huge gains from this in normal code.
Use commute when you can.

这篇关于ref-set vs commute vs alter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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