Skip to content

Instantly share code, notes, and snippets.

@pmbauer
Last active December 19, 2015 21:59
Show Gist options
  • Select an option

  • Save pmbauer/6024216 to your computer and use it in GitHub Desktop.

Select an option

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

pmbauer commented Jul 17, 2013

Copy link
Copy Markdown
Author

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