Last active
December 19, 2015 21:59
-
-
Save pmbauer/6024216 to your computer and use it in GitHub Desktop.
thread ring, clojure core.async style
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(require '[clojure.core.async :refer [chan go <! <!! >! >!!]]) | |
(defn thread-ring [size n] | |
{:pre [(> size 1)]} | |
(let [result (chan 1) | |
[head :as ring] (vec (repeatedly size #(chan 1)))] | |
(dotimes [i size] | |
(let [id (inc i) | |
in (ring i) | |
out (ring (mod id size))] | |
(go (while true | |
(let [m (<! in)] | |
(if (> m 0) | |
(>! out (dec m)) | |
(>! result id))))))) | |
(>!! head n) | |
(<!! result))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It works, is cute, although 1.5x slower than agent-based thread ring.
https://github.com/clojure/test.benchmark/blob/master/src/main/clojure/alioth/thread_ring.clj
(thanks to Tim Baldridge for r2 change to size 1 channels, ~20% speed improvement)