我有以下代碼:這個參考設置有什麼問題?
(ns fwpd.core
(:import java.util.concurrent.Executors))
(def thread-pool
(Executors/newFixedThreadPool
(+ 2 (.availableProcessors (Runtime/getRuntime)))))
(defn dothreads!
[f & {thread-count :threads
exec-count :times
:or {thread-count 1 exec-count 1}}]
(dotimes [t thread-count]
(.submit thread-pool
#(dotimes [_ exec-count] (f)))))
(def all-users (ref {}))
(defn new-user [id login monthly-budget]
{:id id
:login login
:monthly-budget monthly-budget
:total-expense 0})
(defn add-new-user [login monthly-budget]
(dosync
(let [current-user (count @all-users)
user (new-user (inc current-user) login monthly-budget)]
(alter all-users assoc login user))))
當我在REPL加載這一點,並運行以下命令:
(dothreads! #(add-new-user (str (rand-int 500) "name") 5000) :threads 4 :times 4)
我看到,我得到了相同的ID的用戶有時雖然名稱隨機生成,不會像我期望的那樣發生衝突。
我在哪裏錯過了什麼?
我也懷疑這一點,並感謝您的確認和解釋。如圖所示,當用戶發生衝突時,用戶總數實際上會減少,這應該是我的線索。 – ekinmur
沒問題,很高興幫助。 –