在一个网络应用程序中,我试图从一个有限的 id 池中生成一个唯一的线程安全 id。我面临的问题是在读取和写入另一个线程之间可能已经改变了数据结构;这就是为什么我不得不求助于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!
?