简体   繁体   English

Clojure异步-频道中的项目顺序

[英]Clojure async - Order of items in a channel

I'm having some difficulty understanding the output of the following code sample. 我在理解以下代码示例的输出时遇到了一些困难。

(def ch (a/chan 1))

(a/go-loop []
  (Thread/sleep 1000)
  (a/onto-chan ch [1 2 3 4 5] false)
  (recur))

(a/go-loop []
  (Thread/sleep 500)
  (let [val (a/<! ch)]
    (println val))
  (recur))

What I expected to see was a 500ms delay between each number that is printed to the REPL, receiving the numbers 1-5 in order before another range starts printing. 我期望看到的是,每个打印到REPL的数字之间有500ms的延迟,在另一个范围开始打印之前按顺序接收1-5。

However, it appears as though the numbers are interleaving when introducing the Thread/sleep into the go-block that reads from the channel. 但是,当将Thread / sleep引入从通道读取的go-block中时,似乎数字是交错的。 I was under the impression that items are retrieved from a channel in the same order they are put onto the channel? 我给人的印象是,从商品中检索商品的顺序与将商品放入商品中的顺序相同?

Is there something I'm missing? 有什么我想念的吗?

onto-chan executes asynchronously. onto-chan异步执行。 Each execution of your first go-loop basically starts a new process, putting values onto the channel in parallel. 您第一个go-loop每次执行基本上都会启动一个新过程,将值并行地放入通道中。 Note the documentation, which states Returns a channel which will close after the items are copied. 请注意文档,该文档指出Returns a channel which will close after the items are copied.

If you wait for onto-chan to finish, you get the expected result: 如果您等待onto-chan完成,则会获得预期的结果:

(def ch (async/chan 1))

(async/go-loop []
  (Thread/sleep 1000)
  (async/<! (async/onto-chan ch [1 2 3 4 5] false))
  (recur))

(async/go-loop []
  (Thread/sleep 500)
  (when-let [val (async/<! ch)]
    (println val)
    (recur)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM