Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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]
(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