Created
January 4, 2014 20:45
-
-
Save patrickgombert/8260490 to your computer and use it in GitHub Desktop.
Test atomicity
This file contains hidden or 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
(defn swap-items-in [atm v1 v2 i1 i2] | |
(swap! atm | |
(fn [integer-vecs] | |
(let [first-vec (integer-vecs v1) | |
second-vec (integer-vecs v2) | |
first-item (first-vec i1) | |
second-item (second-vec i2) | |
next-first-vec (assoc first-vec i1 second-item) | |
next-second-vec (assoc second-vec i2 first-item)] | |
(assoc | |
(assoc integer-vecs v1 next-first-vec) | |
v2 next-second-vec))))) | |
(testing "swap! is an atomic operation" | |
(let [distinct-items 50 | |
vec-size 10 | |
integer-vecs (vec (map vec (partition vec-size (range distinct-items)))) | |
atm (atom integer-vecs) | |
thread-count 1 | |
iterations-per-thread 100] | |
(dorun | |
(apply pcalls | |
(repeat thread-count | |
#(dotimes [_ iterations-per-thread] | |
(let [v1 (rand-int (/ distinct-items vec-size)) | |
v2 (rand-int (/ distinct-items vec-size)) | |
i1 (rand-int vec-size) | |
i2 (rand-int vec-size)] | |
(swap-items-in atm v1 v2 i1 i2)))))) | |
(is (= (range distinct-items) (sort (flatten (deref atm))))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment