I have the following piece of code
(def number (ref 0))
(dosync (future (alter number inc))) ; A
(future (dosync (alter number inc))) ; B
The 2nd one succeeds, but the first one fails with no transaction is running
. But it is wrapped inside a dosync right?
Does clojure remember opening of transactions based on which thread it was created in ?
You are correct. The whole purpose of dosync
is to begin a transaction in the current thread. The future
runs its code in a new thread, so the alter
in case A is not inside of a dosync
for its thread.
For case B, the alter
and dosync
are both in the same (new) thread, so there is no problem.