エージェントと送信機能で非常に奇妙な動作に遭遇しました。動作を少量のコードに要約しました。
このコード:
(defn weird-behavior
[]
(let [my-agent (agent {:entries nil})]
(doseq [entry [1 2 3]]
(send my-agent assoc :entries (conj (@my-agent :entries) entry)))
(Thread/sleep 100) ;; Allow time for the sends to finish
(println my-agent)))
出力:
#<Agent@222e8b4: {:entries (3)}>
ただし、送信する各呼び出しの間に 10 ミリ秒を与えると、次のようになります。
(defn weird-behavior
[]
(let [my-agent (agent {:entries nil})]
(doseq [entry [1 2 3]]
(send my-agent assoc :entries (conj (@my-agent :entries) entry))
(Thread/sleep 10)))
(Thread/sleep 100) ;; Allow time for the sends to finish
(println my-agent)))
出力は期待どおりです。
#<Agent@6211e63b: {:entries (3 2 1)}>
なぜこうなった?複数のアイテムを連続してエージェントに送信するにはどうすればよいですか?
ありがとう。