I talked about this a bit on the IRC # clojure channel today, but I would like to dwell more on this. Basically, to better understand atoms, swap! , deref and Clojure concurrency in general, I would like to try to write a function that not only returns the value that was replaced using swap! , but also the value that has been replaced.
(def foo (atom 42)) . . . ((fn [a] (do (println "swapped out: " @a) (println "swapped in: "(swap! a rand-int)))) foo)
can print:
swapped out: 42 swapped in: 14
However, if another thread does swap! the same atom between @a deref and the swap! call swap! , then I can replace the value, which is not equal to 42.
How can I write a function that correctly returns both values (swapped and swapped)?
I am not interested in the various meanings that the atom has changed: all I want to know is what was unloaded with the value.
Could this be written using code that is guaranteed to not come to a standstill, and if so, why?
multithreading concurrency atomic clojure
Cedric martin
source share