参考集 vs 通勤 vs 改变 [英] ref-set vs commute vs alter

查看:19
本文介绍了参考集 vs 通勤 vs 改变的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Clojure 中设置 ref 值的 3 种方式有什么区别?我已多次阅读有关 ref-set、comte 和 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-change-functions 来帮助它做出这个决定,这些函数会提示事务之间哪些交互是安全的.

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 正在决定您的事务是否可以安全提交,并且它只在通勤操作上有冲突,而在更改操作上没有冲突,那么它可以继续提交新值,而无需重新启动任何人.这可以避免偶尔的事务重试,尽管您不会在正常代码中看到巨大的收益.
尽可能使用commute.

这篇关于参考集 vs 通勤 vs 改变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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