Created
April 7, 2012 07:06
-
-
Save jhickner/2326125 to your computer and use it in GitHub Desktop.
which is better?
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
;; vanilla version | |
(defn make-lock [] | |
(atom nil)) | |
(defn has-lock? [lock id] | |
(= id @lock)) | |
(defn set-lock! [lock id new-id] | |
(let [lock-id @lock] | |
(if (or (nil? lock-id) (= lock-id id)) | |
(compare-and-set! lock lock-id new-id)))) | |
(def a-lock (make-lock)) | |
(has-lock? a-lock 12) ; >> false | |
(set-lock! a-lock 12) ; >> true | |
;; closure version (is this bad form?) | |
(defn make-lock [] | |
(let [lock (atom nil)] | |
(fn [cmd & args] | |
(apply | |
(condp = cmd | |
:is? (fn [id] (= id @lock)) | |
:set! (fn [id new-id] | |
(let [lock-id @lock] | |
(if (or (nil? lock-id) (= lock-id id)) | |
(compare-and-set! lock lock-id new-id)))) | |
args))))) | |
(def a-lock (make-lock)) | |
(a-lock :is? 12) ; >> false | |
(a-lock :set! 12) ; >> true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment