Reputation: 7327
In Clojure(Script), is there anyway to jam a value at the bottom (as opposed to the top) of a channel so that the next time it is taken from (for example by using <!
inside a go block), it is guaranteed that that the value you jammed into it will be the one that is received?
Upvotes: 1
Views: 124
Reputation: 1057
I'm not sure there is any easy way to do this. You may be able to implement your own type of buffer, as in buffers.clj, and then instantiate your channel using that buffer:
(chan (lifo-buffer 10))
For example you could create a buffer that works like a LIFO queue:
(deftype LIFOBuffer [^LinkedList buf ^long n]
impl/UnblockingBuffer
impl/Buffer
(full? [this]
false)
(remove! [this]
(.removeFirst buf))
(add!* [this itm]
(when-not (>= (.size buf) n)
(.addFirst buf itm))
this)
(close-buf! [this])
clojure.lang.Counted
(count [this]
(.size buf)))
(defn lifo-buffer [n]
(LIFOBuffer. (LinkedList.) n))
Beware, though, that this solution relies on implementation details of core.async
and may break in the future.
Upvotes: 2
Reputation: 6308
You can have two channels, imagine one is called first-class
and the other is called economy
. You write a go-loop
that just recurs and calls alts!
(or alts!!
) on the two channels, but with the :priority
option for first-class
. Then you put values into economy
as your "normal" input channel, and when you want a value to jump the line, you put it into first-class
.
Upvotes: 1