I am new to Functional Programming and Clojure, so I am not really sure about what to do for a project at University. The project should show the advantage of Clojure STM for banking transactions (Transfer of money from account A to account B). So I plan to proceed this way:
[
random-account-source-id(0, N_MAX) ,
random-account-destination-id(0, N_MAX), random-money (0, 1000) ]
for i=0; i lt N; i++;
synchronize: transfer (matrix[i].source,matrix[i].dest,matrix[i].money)
I'm not sure about this, then, maybe:
(defn do-all[]
(dosync
(when (pos? N)
(transfer (get matrix [pos 1], get matrix [pos 2], get matrix [pos 3])))))
Represent the account with a Ref i.e a Ref for each account and perform the money transfer operation in a dosync operation. Also make sure you dont do any side-effect operation (other than on those Refs) in the dosync operation as it may be retried in case of a conflict while updating refs.
Update: In case you will have the number of accounts fixed then you could use ref of vectors where each ref in the vector is an account and each account is identified by the index in the vector.
Ex:
(def total-accounts 100)
(def accounts (vec (map (fn [_] (ref 100)) (range total-accounts))))
In case you have to dynamically add new accounts and identify them by name then you can use hash map where key is the account id (unique value) and value is the Ref for account balance. You will need to wrap this map in a Ref in case you want to do concurrent operations for adding/removing accounts from multiple threads.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With