【发布时间】:2018-02-13 06:51:22
【问题描述】:
此设置与此处的文档直接 不同: https://clojuredocs.org/clojure.core/commute
我将使用我的 cmets 照原样复制代码:
(def counter (ref 0))
(defn alter-inc! [counter]
(dosync (Thread/sleep 100) (alter counter inc)))
(defn commute-inc! [counter]
(dosync (Thread/sleep 100) (commute counter inc)))
(defn bombard-counter! [n f counter]
(apply pcalls (repeat n #(f counter))))
(dosync (ref-set counter 0))
使用 alter 运行会生成随机排序的列表,需要 2000 毫秒,如示例中所示:
> (time (doall (bombard-counter! 20 alter-inc! counter)))
"Elapsed time: 2078.859995 msecs"
(7 6 1 5 4 2 3 9 12 10 8 14 11 13 15 18 16 17 20 19)
但是通勤跑步与官方文档中的说法有很大不同——我得到了重复:
> (time (doall (bombard-counter! 20 commute-inc! counter)))
"Elapsed time: 309.615195 msecs"
(5 1 1 6 5 4 1 8 8 10 10 12 14 13 15 16 17 18 19 20)
这绝对不是文档中承诺的结果!运行时间的差异如宣传的那样,但是重复项呢?我很容易出现拼写错误,所以我从头开始重新做 - 同样的问题。
【问题讨论】:
标签: concurrency clojure