Commits

Michael Lee committed bae15d2

Adding sample Clojure code for reference basics

  • Participants
  • Parent commits 676a4f7

Comments (0)

Files changed (3)

concur/clojure/basics-agents.clj

+;;; agents
+
+(def bond (agent 007))
+
+(send bond inc)
+
+(defn slow-inc [n]
+  (Thread/sleep (rand-int 1000))
+  ;; (println "Incrementing")
+  (+ n 1))
+
+(send bond slow-inc)
+
+(defn multi-send [agt fn n-times]
+  (dorun (apply pcalls
+                (repeat n-times
+                        #(send agt fn)))))
+
+(defn multi-send-and-await [agt fn n-times]
+  (multi-send agt fn n-times)
+  (println "Done sending")
+  (await agt)
+  @agt)

concur/clojure/basics-atoms.clj

+;;; atoms
+
+(def count (atom 0))
+
+(deref count)
+
+@count
+
+(swap! count inc)
+
+(defn slow-inc [n]
+  (Thread/sleep (rand-int 1000))
+  ;; (println "Incrementing ( current val =" n ") in thread"
+  ;;          (.getId (Thread/currentThread)))
+  (+ n 1))
+
+(defn multi-slow-inc [n-threads]
+  (doall (apply pcalls ; "parallel calls"
+                (repeat n-threads
+                        #(swap! count slow-inc)))))

concur/clojure/basics-refs.clj

+;;; refs
+
+(def a (ref 10))
+(def b (ref 20))
+
+(defn foo []
+  (ref-set a 1))
+
+(defn bar []
+  (dosync
+   (ref-set a 30)
+   (alter b inc)))
+
+(defn slow-swap [ref1 ref2]
+  (dosync
+   (let [val1 @ref1
+         val2 @ref2]
+     (Thread/sleep (rand-int 1000))
+     ;; (println "Swapping" val1 "and" val2 "in thread"
+     ;;          (.getId (Thread/currentThread)))
+     (ref-set ref1 val2)
+     (ref-set ref2 val1))))
+
+(defn multi-slow-swap [n-threads]
+  (dorun (apply pcalls
+                (repeat n-threads
+                        #(slow-swap a b)))))