【问题标题】:why the agent is blocked for my code?为什么代理被我的代码阻止?
【发布时间】:2013-08-19 06:23:02
【问题描述】:

说明:
我有一个列表(名为 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  

问题:
代码运行到“等待之前”并阻塞,我猜代理中的操作没有完成,但是为什么?
请让我知道我的代码有什么问题?

【问题讨论】:

  • 你这样做是为了了解代理还是你真的想计算这个?因为有更好的方法可以做到这一点,而不涉及代理(或就此而言的状态)。
  • 代理的每个send 都在代理的(单个)线程上排队一个操作。如果您 send 对该代理执行大量操作,然后向该代理询问 await,那么您将不得不等待队列处理完毕。您并没有像您想象的那样并行执行这些操作。
  • @ivant @A。韦伯你是对的。最好的方法是:(println (reduce + 0 (pmap #(reduce + 0 %) (partition 3 3 [0] large-number-list))))
  • @mingw 见reducers/fold。

标签: clojure


【解决方案1】:

我认为问题出在这一行:

(def total (apply + result))

应该是:

(def total (apply + @result))

实际上并不是阻塞,而是抛出异常。

另一个注意事项:您应该考虑在doin3 中使用recur,而不是直接调用,因为它已经处于尾部位置。

【讨论】:

    猜你喜欢
    • 2017-01-26
    • 2011-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多