Skip to content

Instantly share code, notes, and snippets.

@lagenorhynque
Created March 28, 2019 07:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lagenorhynque/e35d479dc3c34beb9d8301a293004868 to your computer and use it in GitHub Desktop.
Save lagenorhynque/e35d479dc3c34beb9d8301a293004868 to your computer and use it in GitHub Desktop.
dev> (let [count (volatile! 0)
t1 (Thread. #(dotimes [_ 1000] (vswap! count inc)))
t2 (Thread. #(dotimes [_ 1000] (vswap! count inc)))]
(.start t1)
(.start t2)
(.join t1)
(.join t2)
@count)
1577
dev> (let [count (atom 0)
t1 (Thread. #(dotimes [_ 1000] (swap! count inc)))
t2 (Thread. #(dotimes [_ 1000] (swap! count inc)))]
(.start t1)
(.start t2)
(.join t1)
(.join t2)
@count)
2000
dev> (let [answer-ready? (volatile! false)
answer (volatile! 0)
t1 (Thread. #(do (vreset! answer-ready? true)
(vreset! answer 42)))
t2 (Thread. #(if @answer-ready?
(println "The meaning of life is:" @answer)
(println "I don't know the answer")))]
(.start t1)
(.start t2)
(.join t1)
(.join t2))
The meaning of life is: 42
nil
dev> (let [answer-ready? (ref false)
answer (ref 0)
t1 (Thread. #(dosync (ref-set answer-ready? true)
(ref-set answer 42)))
t2 (Thread. #(if @answer-ready?
(println "The meaning of life is:" @answer)
(println "I don't know the answer")))]
(.start t1)
(.start t2)
(.join t1)
(.join t2))
I don't know the answer
nil
@lagenorhynque
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment