Last active
May 8, 2019 14:32
-
-
Save alifarazz/0852349a3514f1b22ca51171a5bdfdac to your computer and use it in GitHub Desktop.
Given 4 bank accounts and 10 accountants, write a program to simulate the withdrawal and deposits done by accountants.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns bank-acc-sim.core | |
(:gen-class)) | |
(import '(java.util.concurrent Executors)) | |
(defn bank-sim [naccounts nthreads init-val niters] | |
(let [refs (map ref (repeat naccounts init-val)) | |
pool (Executors/newFixedThreadPool nthreads) | |
tasks (map | |
(fn [tid] | |
(fn [] | |
(dotimes [n niters] | |
(let [src (rand-int naccounts) | |
dest (rand-int naccounts) | |
offset (rand-int 10)] | |
(dosync | |
(alter (nth refs src) (fn [v] (- v offset))) | |
(alter (nth refs dest) (fn [v] (+ v offset)))))))) | |
(range nthreads))] | |
(doseq [future (.invokeAll pool tasks)] | |
(.get future)) | |
(.shutdown pool) | |
(map deref refs))) | |
;; (bank-sim 4 10 1000 (* 10 1000)) | |
(defn -main | |
"Eh..." | |
[& args] | |
(let [res (bank-sim 4 10 1000 (* 10 1000))] | |
(println res) | |
(println (reduce + res))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment