Guest User

clojure stm

a guest
Feb 19th, 2012
196
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.  
  2. (def a (ref 0))
  3. (def b (ref 0))
  4.  
  5. (def val-seq (atom []))
  6.  
  7. (def commute-a-count (atom 0))
  8. (defn commute-a []
  9.   (dosync
  10.    (swap! commute-a-count inc)
  11.    (Thread/sleep 60)
  12.    (commute a inc)
  13.    (swap! val-seq conj [@a @b])))
  14.  
  15. (def alter-b-count (atom 0))
  16. (defn alter-b []
  17.   (dosync
  18.    (swap! alter-b-count inc)
  19.    (Thread/sleep 70)
  20.    (alter b inc)
  21.    (swap! val-seq conj [@a @b])))
  22.  
  23. (def commute-a-alter-b-count (atom 0))
  24. (defn commute-a-alter-b []
  25.   (dosync
  26.    (swap! commute-a-alter-b-count inc)
  27.    (Thread/sleep 100)
  28.    (commute a (partial + 0.07))
  29.    (alter b (partial + 0.07))
  30.    (swap! val-seq conj [@a @b])))
  31.  
  32. (let [threads [(Thread. (fn []
  33.                           (dotimes [_ 3]
  34.                             (commute-a))))
  35.                (Thread. (fn []
  36.                           (dotimes [_ 3]
  37.                             (commute-a-alter-b))))
  38.                (Thread. (fn []
  39.                           (dotimes [_ 3]
  40.                             (alter-b))))]]
  41.   (doseq [t threads]
  42.     (.start t))
  43.   (doseq [t threads]
  44.     (.join t)))
  45.  
  46. (doseq [v @val-seq]
  47.   (println v))
  48. (println "commute-a: " @commute-a-count)
  49. (println "alter-b: " @alter-b-count)
  50. (println "commute-a-alter-b: " @commute-a-alter-b-count)
  51.  
  52. ;; Result:
  53. ;; [1 0]
  54. ;; [1.07 0.07]
  55. ;; [2.0700000000000003 0.07]
  56. ;; [2.14 0.14]
  57. ;; [3.14 0.07]
  58. ;; [2.14 1.1400000000000001]
  59. ;; [3.14 2.14]
  60. ;; [3.14 3.14]
  61. ;; [3.21 3.21]
  62. ;; commute-a:  4
  63. ;; alter-b:  6
  64. ;; commute-a-alter-b:  6
Advertisement
Add Comment
Please, Sign In to add comment