【问题标题】:Why does `core.async/pipeline` return a channel?为什么`core.async/pipeline`返回一个通道?
【发布时间】:2016-11-07 20:16:06
【问题描述】:

我刚刚注意到pipeline 系列返回一个channel,它的运行似乎完全独立于管道的目的及其相关通道。

请注意,在以下示例中,您可以将>! / <!pipesa> / b> 分开,它们是不相关的。

据我了解,pipelines 应该是空操作,并在设置从a>b> 的副作用transduction 时返回nil

那么,我错过了什么,为什么pipeline 返回channel

(def a> (chan))
(def b> (chan))
(def pipes (pipeline-blocking 4
                     b>
                     (map clojure.string/upper-case)
                     a>))
(go (>! pipes "hello world"))
(go (println "Pipes: " (<! pipes)))
(go (>! a> "apples are gooood"))
(go (println "B: " (<! b>)))

【问题讨论】:

    标签: clojure core.async


    【解决方案1】:

    当没有更多要复制的元素时,您会返回一个关闭的通道。也就是说,在关闭a&gt; 并且其中的所有元素都已变为大写并放置在b&gt; 上之后。您可以从生成的频道中&lt;! 了解流水线操作何时完成,如果您关心,或者您可以丢弃频道。你可能不应该写信给它。

    这是许多异步操作的常见模式,并且确实经常隐式发生:每个go 块返回一个通道,该通道在块完成时写入块的返回值,并且许多异步操作使用@ 987654325@ 块作为它们的返回值,因此您会自动获得这个“工作完成”通道。

    【讨论】:

    • 这是有道理的,并且给了我足够的时间进行实验,我将其作为答案与您的答案一起发布。如果我的解释无效,请告诉我!
    【解决方案2】:

    为了解释@amalloy 的答案,在下面的示例中,a&gt;b&gt; 在能够完成时将true 放在它们上面。由于chan&gt; 没有缓冲,它们无法完成,直到另一个进程退出它们,即最后的println

    如果chan&gt; 被缓冲,a&gt;b&gt; 可以立即&gt;!,所以立即打印。

    (def chan> (chan 4))
    (def a> (go (>! chan> "Apple")))
    (go (println "from a>: " (<! a>)))
    (def b> (go (>! chan> "Ball")))
    (go (println "from b>: " (<! b>)))
    
    (go (println "from chan>: "(<! chan>)))
    ;; => from chan>: Apple
    ;; => from a>: true
    (go (println "from chan>: "(<! chan>)))
    ;; => from chan>: Ball
    ;; => from b>: true
    

    这与pipelines 背后的想法相同。


    ;; Pipeline-specific
    
    (def a> (chan))
    (def b> (chan))
    (def p> (pipeline 4 b> (map clojure.string/upper-case) a>))
    
    ;; this won't happen until `a>` `close!`s
    (go (println "pipeline is done: " (<! p>)))
    
    ;; execute the following 2 lines ad lib
    (go (>! a> "hi there"))
    (go (println "from b>: " (<! b>)))
    
    (comment
      (close! a>) ; triggers the "pipeline is done"
      (close! b>)) ; doesn't trigger it, but `b>` now only returns nil when taking
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-22
      • 2015-10-29
      • 2015-07-11
      • 1970-01-01
      • 2017-06-12
      • 2011-12-17
      相关资源
      最近更新 更多