4 ms·
Identities change their associated values (state) by transactions. That means that from the viewpoint of concurrent observers (threads), partial or interrupted
by vnorilo 7y ago
Identities change their associated values (state) by transactions. That means that from the viewpoint of concurrent observers (threads), partial or interrupted updates are never seen - the update is either 0% or 100% completed.
In Software Transactional Memory, that can be accomplished with atomic swaps. In Clojure, a new value, no matter how large, is constructed and the transaction is completed by repointing a mutable reference (ref or atom) to the new value atomically. Clojure has plenty of tools for constructing such transactions, such as `update-in` [1].
In order to make this work well, we need to be able to make collections behave like values. So, when you associate a value to a key in a Clojure collection, the original collection is unmodified and a new version is returned. This plays well into updating collections with STM - you just swap the root reference to a new collection.
Any transactions must be indempotent, that is, not touch the program state in any way, just produce a new value - because the STM system might need to retry the transaction. Retries happen when multiple threads try to modify a bit of shared state. In Clojure, `swap!` [2] is the actual mutation bit. You provide the transaction function to `swap!`, which produces a new value from the current state of a mutable reference. If, during the computation, another thread has swapped in a new value, the transaction is retried based on that updated value. On some architectures, this system can be implemented without locks, using the atomic compare-swaps of the hardware. The happy path of no conflicts is very efficient, while a heavily contested updates will result in redundant discarded (due to retry) transactions.
Please let me know if I can better explain anything!
[1] https://clojuredocs.org/clojure.core/update-in https://clojuredocs.org/clojure.core/update-in
[2] https://clojuredocs.org/clojure.core/swap https://clojuredocs.org/clojure.core/swap!
- 6thaccount2 7y agoThis is really good and thank you kind internet stranger!