描述:
我有一个列表(名为 large-number-list),其中包含许多数字,我想得到这些数字的总和。
现在我将列表分成三个元素作为一组进行计算(该组将在代理的动作中计算),并将这三个元素的总和放入一个向量(命名为结果)。
最后,我将向量中的元素累积在一起。
代码如下:
;use agent to calculate many number
(def result (agent []))
(def large-number-list [1 2 3 4 5 6 7 8 9 10 11 12]);assume that large-number-list contains many number in it
(defn doin3 [col do-fn]
(let [[x1 x2 x3 & rest-elem] col
rest-len (count rest-elem)]
(println "x1 x2 x3" x1 x2 x3)
(println "rest-len is " rest-len)
(do-fn x1 x2 x3)
(when (> rest-len 0) (doin3 rest-elem do-fn))))
;assume that the calculate is a time-consumed operation
(defn calculate [v x1 x2 x3]
(conj v (+ x1 x2 x3)))
(doin3 large-number-list #(send result calculate %1 %2 %3))
(println "before await")
(await result)
(println "after await")
(println @result)
(def total (apply + result))
(println "total is:" total)
(shutdown-agents)
预期输出:
x1 x2 x3 1 2 3
rest-len is 9
x1 x2 x3 4 5 6
rest-len is 6
x1 x2 x3 7 8 9
rest-len is 3
x1 x2 x3 10 11 12
rest-len is 0
before await
after await
total is: 78
实际输出:
x1 x2 x3 1 2 3
rest-len is 9
x1 x2 x3 4 5 6
rest-len is 6
x1 x2 x3 7 8 9
rest-len is 3
x1 x2 x3 10 11 12
rest-len is 0
before await
问题:
代码运行到“等待之前”并阻塞,我猜代理中的动作没有完成,但为什么呢?
请让我知道我的代码有什么问题?