在一个Web应用程序中,我正试图从有限的ID池中生成唯一的线程安全ID。我面临的问题是,在读取和写入之间,另一个线程可能已经更改了数据结构;这就是为什么我必须使用
有没有更简单的方式在不需要手动进行STM操作且不滥用
compare-and-set!
的原因。(def sid-batch 10)
(def sid-pool (atom {:cnt 0
:sids '()}))
(defn get-sid []
(let [{:keys [cnt sids] :as old} @sid-pool]
; use compare-and-set! here for atomic read & write
(if (empty? sids)
; generate more sids
(if (compare-and-set!
sid-pool
old
(-> old
(assoc :sids (range (inc cnt) (+ sid-batch cnt)))
(assoc :cnt (+ cnt sid-batch))))
; return newest sid or recur till "transaction" succeeds
cnt
(recur))
; get first sid
(if (compare-and-set! sid-pool old (update-in old [:sids] next))
; return first free sid or recur till "transaction" succeeds
(first sids)
(recur)))))
有没有更简单的方式在不需要手动进行STM操作且不滥用
sid-pool
中的字段作为swap!
的返回值的情况下,实现读写同步?