Skip to content

Instantly share code, notes, and snippets.

@na-ka-na
Created August 29, 2010 20:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save na-ka-na/556679 to your computer and use it in GitHub Desktop.
Save na-ka-na/556679 to your computer and use it in GitHub Desktop.
(ns tt)
(defn deduct-money-from-accnt
[a1-ref a2-ref {:keys [ensure1 ensure2]}]
(dosync
(when ensure1 (ensure a1-ref))
(when ensure2 (ensure a2-ref))
(let [sum (- (+ @a1-ref @a2-ref) 200)]
(when (>= sum 0)
(alter a1-ref - 200)))))
(defn deduct-money-concurrently
[a1-ref a2-ref m]
(let [fut1 (future (deduct-money-from-accnt a1-ref a2-ref m))
fut2 (future (deduct-money-from-accnt a2-ref a1-ref m))]
(deref fut1)
(deref fut2)
(println (str "Amounts=[" @a1-ref "," @a2-ref "]"))))
(defn transaction-simul
[{:keys [ensure1 ensure2] :as m}]
(dorun (repeatedly 10 #(time (deduct-money-concurrently (ref 100) (ref 100) m)))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment