Created
June 9, 2018 18:00
-
-
Save aj07mm/9a02f556b4c6b1d04a6faaf3fc0e2a7a to your computer and use it in GitHub Desktop.
commute.clj
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| (ns testing.core) | |
| (def start (atom 0)) ; Record start time. | |
| (def c1 (ref 0)) ; Counter 1 | |
| (def c2 (ref 0)) ; Counter 2 | |
| (def c3 (ref 0)) ; Counter 3 | |
| (defn milliTime | |
| "Get current time in millisecond." | |
| [] | |
| (int (/ (System/nanoTime) 1000000))) | |
| (defn lap | |
| "Get elapse time since 'start' in millisecond." | |
| [] | |
| (- (milliTime) @start)) | |
| (defn slow-inc | |
| "Slow increment, takes 1 second." | |
| [x x-name] | |
| (println "slow-inc beg" x-name ":" x "|" (lap) "ms") | |
| (Thread/sleep 1000) | |
| (println "slow-inc end" x-name ":" (inc x) "|" (lap) "ms") | |
| (inc x)) | |
| (defn fast-inc | |
| "Fast increment. The value it prints is incremented." | |
| [x x-name] | |
| (println "fast-inc " x-name ":" (inc x) "|" (lap) "ms") | |
| (inc x)) | |
| (defn -main | |
| [] | |
| ;; Initialize c1, c2, c3 and start. | |
| (dosync (ref-set c1 0) | |
| (ref-set c2 0) | |
| (ref-set c3 0)) | |
| (reset! start (milliTime)) | |
| ;; Start two new threads simultaneously. | |
| (let [t1 (future | |
| (dosync | |
| (println "transaction start |" (lap) "ms") | |
| (alter c1 slow-inc "c1") | |
| (alter c2 slow-inc "c2") | |
| (alter c3 slow-inc "c3") | |
| (println "transaction end |" (lap) "ms"))) | |
| t2 (future | |
| (Thread/sleep 900) ; Increment at 900 ms | |
| (dosync (alter c3 fast-inc "c3")))] | |
| ;; Dereference all of them (wait until all 2 threads finish). | |
| @t1 @t2 | |
| ;; Print final counters' values. | |
| (println "c1 :" @c1) | |
| (println "c2 :" @c2) | |
| (println "c3 :" @c3))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment