Skip to content

Instantly share code, notes, and snippets.

@pmbauer
Last active December 19, 2015 21:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pmbauer/6024216 to your computer and use it in GitHub Desktop.
Save pmbauer/6024216 to your computer and use it in GitHub Desktop.
thread ring, clojure core.async style
(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)))
@pmbauer
Copy link
Author

pmbauer commented Jul 17, 2013

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)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment