Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- (def a (ref 0))
- (def b (ref 0))
- (def val-seq (atom []))
- (def commute-a-count (atom 0))
- (defn commute-a []
- (dosync
- (swap! commute-a-count inc)
- (Thread/sleep 60)
- (commute a inc)
- (swap! val-seq conj [@a @b])))
- (def alter-b-count (atom 0))
- (defn alter-b []
- (dosync
- (swap! alter-b-count inc)
- (Thread/sleep 70)
- (alter b inc)
- (swap! val-seq conj [@a @b])))
- (def commute-a-alter-b-count (atom 0))
- (defn commute-a-alter-b []
- (dosync
- (swap! commute-a-alter-b-count inc)
- (Thread/sleep 100)
- (commute a (partial + 0.07))
- (alter b (partial + 0.07))
- (swap! val-seq conj [@a @b])))
- (let [threads [(Thread. (fn []
- (dotimes [_ 3]
- (commute-a))))
- (Thread. (fn []
- (dotimes [_ 3]
- (commute-a-alter-b))))
- (Thread. (fn []
- (dotimes [_ 3]
- (alter-b))))]]
- (doseq [t threads]
- (.start t))
- (doseq [t threads]
- (.join t)))
- (doseq [v @val-seq]
- (println v))
- (println "commute-a: " @commute-a-count)
- (println "alter-b: " @alter-b-count)
- (println "commute-a-alter-b: " @commute-a-alter-b-count)
- ;; Result:
- ;; [1 0]
- ;; [1.07 0.07]
- ;; [2.0700000000000003 0.07]
- ;; [2.14 0.14]
- ;; [3.14 0.07]
- ;; [2.14 1.1400000000000001]
- ;; [3.14 2.14]
- ;; [3.14 3.14]
- ;; [3.21 3.21]
- ;; commute-a: 4
- ;; alter-b: 6
- ;; commute-a-alter-b: 6
Advertisement
Add Comment
Please, Sign In to add comment