【问题标题】:Placing a value at the bottom of a channel?在通道底部放置一个值?
【发布时间】:2016-01-23 08:56:13
【问题描述】:

在 Clojure(Script) 中,无论如何都会在通道的底部(而不是顶部)阻塞一个值,以便下次从它获取(例如通过在 go 块中使用 <! ),保证你塞进去的值就是收到的那个吗?

【问题讨论】:

    标签: clojure clojurescript core.async


    【解决方案1】:

    我不确定是否有任何简单的方法可以做到这一点。您可以实现自己的缓冲区类型,如buffers.clj,然后使用该缓冲区实例化您的通道:

    (chan (lifo-buffer 10))
    

    例如,您可以创建一个类似于 LIFO 队列的缓冲区:

    (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))
    

    但请注意,此解决方案依赖于 core.async 的实现细节,并且将来可能会中断。

    【讨论】:

      【解决方案2】:

      你可以有两个频道,假设一个叫做first-class,另一个叫做economy。你写了一个go-loop,它只是在两个通道上重复并调用alts!(或alts!!),但:priority选项用于first-class。然后将值放入economy 作为“正常”输入通道,当您想要一个值跳线时,将其放入first-class

      【讨论】:

        猜你喜欢
        • 2013-12-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-01-31
        • 2014-04-29
        相关资源
        最近更新 更多