Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #example of usage of atoms and swap!
- (def counter (atom 0))
- (swap! counter inc)
- ;; @counter -> 0
- ;; @counter -> 1
- ; Let’s create 2 threads that increment counter two times:
- (let [n 2]
- (future (dotimes [_ n] (swap! counter inc)))
- (future (dotimes [_ n] (swap! counter inc))))
- ;; @counter -> 5
- #example of usage of atoms and swap! with side-effects
- (defn inc-print [val thd-id]
- (println “thread“, thd-id, “counter:“, val)
- (inc val))
- Create three threads with printing side-effects. We will see extra print lines from when the swap! needed to retry because of another thread modifying the value before it could set it.
- (def counter (atom 0))
- (let [n 2]
- (future (dotimes [_ n] (swap! counter inc-print :a)))
- (future (dotimes [_ n] (swap! counter inc-print :b)))
- (future (dotimes [_ n] (swap! counter inc-print :c))))
- ;;@counter -> 6
- #example of usage of refs and dosync for creating #transactions which apply alter to update refs
- ;; Create 2 bank accounts
- (def acc1 (ref 100))
- (def acc2 (ref 200))
- ;; How much money is there?
- (println @acc1 @acc2)
- ;; => 100 200
- ;; Either both accounts will be changed or none
- (defn transfer-money [a1 a2 amount]
- (dosync
- (alter a1 - amount)
- (alter a2 + amount)
- amount)) ; return amount from dosync block and function (just for fun)
- ;; Now transfer $20
- (transfer-money acc1 acc2 20)
- ;; => 20
- ;; Check account balances again
- (println @acc1 @acc2)
- ;; => 80 220
- ;; => We can see that transfer was successful
- #Another example with 2 refs
- (def alice-height (ref 1))
- (def right-hand-bites (ref 10))
- (defn eat-from-right-hand []
- (dosync (when (pos? @right-hand-bites)
- (alter right-hand-bites dec)
- (alter alice-height #(* % 2)))))
- (let [n 2]
- (future (dotimes [_ n] (eat-from-right-hand)))
- (future (dotimes [_ n] (eat-from-right-hand)))
- (future (dotimes [_ n] (eat-from-right-hand))))
- @alice-height
- ;; -> 64
- @right-hand-bites
- ;; -> 4
- #example of usage of commute to improve performance
- (def alice-height (ref 1))
- (def right-hand-bites (ref 10))
- (defn eat-from-right-hand []
- (dosync (when (pos? @right-hand-bites)
- (commute right-hand-bites dec)
- (commute alice-height #(* % 2)))))
- (let [n 3]
- (future (dotimes [_ n] (eat-from-right-hand)))
- (future (dotimes [_ n] (eat-from-right-hand)))
- (future (dotimes [_ n] (eat-from-right-hand))))
- @alice-height
- ;; -> 512
- @right-hand-bites
- ;; -> 1
Advertisement
Add Comment
Please, Sign In to add comment