Skip to content

Instantly share code, notes, and snippets.

@angusiguess
Created February 26, 2013 23:26
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 angusiguess/5043335 to your computer and use it in GitHub Desktop.
Save angusiguess/5043335 to your computer and use it in GitHub Desktop.
Supporting code for a talk on STM in Clojure
(ns stm-talk.core)
;;This creates our ledger
(def ledger (ref {}))
(defn journal
"Apply a debit and credit simultaneously to a given account."
[debit credit amount]
(dosync
(when (nil? (@ledger debit)) (alter ledger assoc debit 0))
(when (nil? (@ledger credit)) (alter ledger assoc credit 0))
(alter ledger update-in [debit] + amount)
(alter ledger update-in [credit] - amount)))
(defn accountant []
(let [debits [:cash :accts-recv :salesrev :otherassets]
credits [:accts-payable :loans-payable :otherliabilities :sales]]
(journal (rand-nth debits) (rand-nth credits) (rand-int 4000))))
(dorun (apply pcalls (repeat 1000000 accountant)))
(defn balance [] (reduce #(+ %1 (second %2)) 0 @ledger))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment