Clojure STM ambiguity factor

三世轮回 提交于 2020-01-14 10:13:39

问题


In Clojure we use STM for Concurrency.

My question is STM uses point in time value of data , isn't this introduce ambiguity ?

How could we know what value is accessed ?


回答1:


The STM in Clojure provides (through refs and dosync) a transaction context where all updates are guaranteed to be made "at the same time" to all the refs involved when viewed from the outside world.

The objective is to maintain consistency of the values in the system, the typical example is the transfer of money between two bank accounts. If you are transferring, say, 100 dollars from account A to account B, then you'll want to have the amounts for A and B changed simultaneously.

In this example there's actually no ambiguity in the values read for the amounts that are being handled inside the transaction, because only the following situations are possible at the moment the read from outside the transaction is done:

  1. The transaction has begun but is not yet finished, so the values have not been "officially" changed. The transaction can later be committed or retried, but when you read them, that was the state of each account.
  2. The transaction has finished so the amounts read are the modified values.

When inside the transaction, the refs you only read (and don't modify) could change their value from one point of the transaction to the other, this is called write skew (see Clojure Programming - Chapter 4, Refs, Write Skew). In order to avoid this you can use ensure (instead of deref), this will cause that if the value for any of these refs changes (the ones you only read), then the whole transaction will be retried.




回答2:


Clojurians use the words 'time' and 'value' with very specific meanings in this context to remove such ambiguity. In this context 'time' is 'time in a sequence' or epochal time rather than time as in time on the wall. So time describes which value in the sequence of values for this identity.

Value is the unchanging contents of an identity at a point in time. This value can be simple (a primitive or atomic value) or compound and made of arbitrarily structured unchanging values. The important part is that values do not change so if you want to know which value was used you can simply print or log it

I highly reccommend this video on values, state and identity



来源:https://stackoverflow.com/questions/17195959/clojure-stm-ambiguity-factor

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!