Data commit
This commit is contained in:
parent
7387c8f97b
commit
cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions
7
Task/Atomic-updates/Clojure/atomic-updates-1.clj
Normal file
7
Task/Atomic-updates/Clojure/atomic-updates-1.clj
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
(defn xfer [m from to amt]
|
||||
(let [{f-bal from t-bal to} m
|
||||
f-bal (- f-bal amt)
|
||||
t-bal (+ t-bal amt)]
|
||||
(if (or (neg? f-bal) (neg? t-bal))
|
||||
(throw (IllegalArgumentException. "Call results in negative balance."))
|
||||
(assoc m from f-bal to t-bal))))
|
||||
2
Task/Atomic-updates/Clojure/atomic-updates-2.clj
Normal file
2
Task/Atomic-updates/Clojure/atomic-updates-2.clj
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
(def *data* (atom {:a 100 :b 100})) ;; *data* is an atom holding a map
|
||||
(swap! *data* xfer :a :b 50) ;; atomically results in *data* holding {:a 50 :b 150}
|
||||
22
Task/Atomic-updates/Clojure/atomic-updates-3.clj
Normal file
22
Task/Atomic-updates/Clojure/atomic-updates-3.clj
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
(defn equalize [m a b]
|
||||
(let [{a-val a b-val b} m
|
||||
diff (- a-val b-val)
|
||||
amt (/ diff 2)]
|
||||
(xfer m a b amt)))
|
||||
|
||||
(defn randomize [m a b]
|
||||
(let [{a-val a b-val b} m
|
||||
min-val (min a-val b-val)
|
||||
amt (rand-int (- min-val) min-val)]
|
||||
(xfer m a b amt)))
|
||||
|
||||
(defn test-conc [f data a b n name]
|
||||
(dotimes [i n]
|
||||
(swap! data f a b)
|
||||
(println (str "total is " (reduce + (vals @data)) " after " name " iteration " i))))
|
||||
|
||||
(def thread-eq (Thread. #(test-conc equalize *data* :a :b 1000 "equalize")))
|
||||
(def thread-rand (Thread. #(test-conc randomize *data* :a :b 1000 "randomize")))
|
||||
|
||||
(.start thread-eq)
|
||||
(.start thread-rand)
|
||||
Loading…
Add table
Add a link
Reference in a new issue