I try my code on my machine.
1. deref version
(defn funk [r]
(dosync
(println "Start:" @r)
(Thread/sleep 10000)
(println "End:" @r)))
user> (.start (Thread. #(funk r)))
Start: 1
nil
user> (dosync (ref-set r 5))
Start: 5
End: 5
5
Actually, when I type in (dosync (ref-set r 5)), I got 5 soon. After a
few seconds, it prints out the "Start: 5". And after another few
seconds, print out " End: 5". So yes, the funk transcation is redone.
2. Ensure version
(defn funk [r]
(dosync
(println "Start:" (ensure r))
(Thread/sleep 10000)
(println "End:" (ensure r))))
user> (.start (Thread. #(funk r)))
Start: 1
nil
user>user> (dosync (ref-set r 5))
End: 1
5
When I type in the (dosync (ref-set r 5)), that transcation was
blocked. So it is run after the funk finished.
So I can guess that, If you use deref, there can be multipule
transcation running at once. But sometimes transcation must be rerun.
If you use ensure, only one transcation is run. Others are blocked.
Is it true?
Thanks for all your help!
Sincerely,
Jack
On 2月21日, 下午10时26分, Michał Marczyk <[email protected]> wrote:
> On 21 February 2010 14:13, Michael Wood <[email protected]> wrote:
>
> > That does demonstrate the difference (or a difference), but I don't
> > get 3 printlns.
>
> Ouch, I actually posted the wrong version of the function. Here's an
> improvement in the context of a REPL interaction:
>
> 1. ensure version:
>
> user> (defn funk [r]
> (dosync
> (println (ensure r))
> (Thread/sleep 5000)
> (println (ensure r))))
> #'user/funk
> user> (def r (ref 1))
> #'user/r
> user> (.start (Thread. #(funk r)))
> 1
> nil
> user> (dosync (ref-set r 5))
> 1
> 5
>
> 2. deref version:
>
> user> (defn funk [r]
> (dosync
> (println @r)
> (Thread/sleep 5000)
> (println @r)))
> #'user/funk
> user> (def r (ref 1))
> #'user/r
> user> (.start (Thread. #(funk r)))
> 1
> nil
> user> (dosync (ref-set r 5))
> 5
> 5
> 5
>
> Note how the deref version prints more lines (because it retries the
> transaction).
>
> I'm using a newer commit (49a7d6b8e14050a45df5332e768ba6647752215d),
> but this shouldn't make any difference.
>
> Sincerely,
> Michał
--
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to [email protected]
Note that posts from new members are moderated - please be patient with your
first post.
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en