简体   繁体   中英

Race condition in Clojure stm?

Hello I was reading the book joy of clojure and in the section about the STM they have an image of 2 transactions where A is initially retrieving the same value from a ref as B is and then both transaction A and B does their calculations but A finishes first and makes the commit to the variable and thus B must retry.

But what I am pondering about is if B would have retried with A's commit. And if that is the case then what if it where the opposite? Then the final value would be significally different.

This seems to simple of a hazard to have been overlooked,and I believe I don't understand it completely. Please help me untangle this.

Let's look at example:

(defn test-trans []
  (let [x (ref 1)
        t-inc #(dosync (alter x inc))
        t-mul #(dosync (alter x (partial * 2)))
        fns (flatten (repeat 10 [t-mul t-inc]))]
    (last (pmap (fn [f] (f)) fns))
    @x))

Here we have 2 transactional functions - increase x by 1 and multiply x by 2. We apply 20 such functions (10 of each kind) in parallel and observe final value of ref . Indeed results are different for each run:

=> (test-trans)
2418
=> (test-trans)
2380
=> (test-trans)
1804
=> (test-trans)
4210

Actually this is correct behaviour. STM guarantees that code will be executed without locks and changes are applied atomically (they cannot be applied only partially). However it does not guarantee that we will have the same result for different order of transactions.

Clojure provides great parallel programming instruments which simplify writing of correct code a lot. But avoiding this kind of race conditions is responsibility of developer (in fact, such cases are clear sign of bad system design).

Another example from SQL:

DELETE FROM tbl WHERE col=1
UPDATE tbl SET col=2 WHERE col=1

If these queries are executed in parallel, then no matter what isolation level will be used for transactions - result will depend on the order.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM