Skip to content

Instantly share code, notes, and snippets.

@nishio
Created June 5, 2012 10:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nishio/2874143 to your computer and use it in GitHub Desktop.
Save nishio/2874143 to your computer and use it in GitHub Desktop.
;
; STMの挙動を観察する
; スレッドを作るマクロ
; http://code.google.com/p/javaee-study/source/browse/trunk/clojure-concurrency/concurrency.clj?r=5
(import '(java.lang Thread))
(defmacro with-new-thread [& body]
`(.start (Thread. (fn [] ~@body))))
; 指定された値がTrueになるまでブロックするチェックポイント
(def dict (new java.util.Hashtable))
(defn checkpoint [key]
(while (not (.get dict key))
(Thread/sleep 100)))
(defn open [key]
(.put dict key true)
(println "open" key))
; STM
(def rx (ref 0))
(with-new-thread
(dosync
(println "start transaction 1")
(checkpoint "11") ; block
(ref-set rx 1)
(println "modified ref rx: 1")
(checkpoint "12") ; block
(println "finish transaction 1")
))
(with-new-thread
(dosync
(println "start transaction 2")
(checkpoint "21") ; block
(ref-set rx 2)
(println "modified ref rx: 2")
(checkpoint "22") ; block
(println "finish transaction 2")
))
(Thread/sleep 500)
(println "----------")
(Thread/sleep 500)
(open "11")
(Thread/sleep 500)
(println "----------")
(Thread/sleep 500)
(open "21")
(Thread/sleep 500)
(println "----------")
(Thread/sleep 500)
(open "12")
(Thread/sleep 500)
(println "----------")
(Thread/sleep 500)
(open "22")
;output----------
$ java -jar clojure-1.4.0.jar stm.clj
start transaction 1
start transaction 2
----------
open 11
modified ref rx: 1
----------
open 21
start transaction 2
start transaction 2
start transaction 2
start transaction 2
----------
start transaction 2
start transaction 2
start transaction 2
start transaction 2
start transaction 2
start transaction 2
open 12
finish transaction 1
start transaction 2
modified ref rx: 2
----------
open 22
finish transaction 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment