我在 Clojure 中编写了一些 core.async 代码,当我运行它时,它消耗了所有可用内存并因错误而失败。似乎mapcat
在 core.async 管道中使用会破坏背压。(由于超出此问题范围的原因,这是不幸的。)
下面是一些代码,通过计算ing 转换器:x
的进出数来演示该问题:mapcat
(ns mapcat.core
(:require [clojure.core.async :as async]))
(defn test-backpressure [n length]
(let [message (repeat length :x)
input (async/chan)
transform (async/chan 1 (mapcat seq))
output (async/chan)
sent (atom 0)]
(async/pipe input transform)
(async/pipe transform output)
(async/go
(dotimes [_ n]
(async/>! input message)
(swap! sent inc))
(async/close! input))
(async/go-loop [x 0]
(when (= 0 (mod x (/ (* n length) 10)))
(println "in:" (* @sent length) "out:" x))
(when-let [_ (async/<! output)]
(recur (inc x))))))
=> (test-backpressure 1000 10)
in: 10 out: 0
in: 2680 out: 1000
in: 7410 out: 2000
in: 10000 out: 3000 ; Where are the other 7000 characters?
in: 10000 out: 4000
in: 10000 out: 5000
in: 10000 out: 6000
in: 10000 out: 7000
in: 10000 out: 8000
in: 10000 out: 9000
in: 10000 out: 10000
生产者远远领先于消费者。
看来我不是第一个发现这一点的人。但是这里给出的解释似乎并没有完全涵盖它。(尽管它确实提供了一个足够的解决方法。)从概念上讲,我希望生产者领先,但只是通道中可能缓冲的少数消息的长度。
我的问题是,所有其他消息在哪里?到第四行输出 7000 :x
s 下落不明。