Clojure agent & send

(def counter (agent 0)) ;; agent
(defn heavy-inc [x]
  (Thread/sleep 1000)
  (inc x))

(send counter #(heavy-inc %)) ;; send
(send counter #(heavy-inc %))
(send counter #(heavy-inc %))

(println @counter)
(await counter) ;; await
(println @counter)

実行結果は 「0」 のあとに数秒たってから 「3」が出力される。

counterは、非同期処理で更新できるように agent にしている。
send は、とある関数をつかって、agent の状態を更新できる。
send の呼び出し時点では、重いお仕事を直接実行せずに、処理依頼のみ。お仕事をキューに積んでいる。
うらでお仕事が実行される。await は 重たい仕事が終わるまで待っている。
counter は整合性を保つ必要があるため、直列で お仕事しているようだった。試しに、counter-a, counter-b で2つのagentを用意して、それぞれ sendしたら、思ったように処理時間が変わった。
ちゃんと時間計測してないが。

プログラミングClojure

プログラミングClojure