在制作频道时,如下所示:
(chan 10 tx)
如果我创建了10个这样的通道,然后同时向所有人发送消息,那么传感器将如何执行。它们会同时运行还是在一个线程上运行?
答案 0 :(得分:1)
我认为现在没有定义传感器运行时的行为,但是查看ManyToManyChannel的实现,传感器(add!
字段)可以同时被调用从频道写作和阅读。
运行一个简单的测试似乎如果通道未满,写入线程将执行传感器,但如果通道已满,有时读取线程会运行它。
缓冲区小的样本:
(defn thread-name []
(.getName (Thread/currentThread)))
(require '[clojure.core.async :as async :refer [chan <! >! >!! go]])
(defn p [& args]
(locking *out*
(apply println (thread-name) ":" args)))
(defn log [v]
(p "Transforming" v)
v)
(def tx (map log))
(def c (chan 1 tx))
(def c2 (chan 1 tx))
(go
(loop []
(when-let [v (<! c)]
(p "Getting from c1" v)
(<! (async/timeout 100))
(recur))))
(go
(loop []
(when-let [v (<! c2)]
(p "Getting from c2" v)
(<! (async/timeout 100))
(recur))))
(dotimes [_ 5]
(p "Putting in c1" 1)
(>!! c 1)
(p "Putting in c2" 100)
(>!! c2 100))
产生输出:
nREPL-worker-20 : Transforming 1
nREPL-worker-20 : Putting in c2 100
async-dispatch-33 : Getting from c1 1
nREPL-worker-20 : Transforming 100
nREPL-worker-20 : Putting in c1 1
async-dispatch-31 : Getting from c2 100
nREPL-worker-20 : Transforming 1
nREPL-worker-20 : Putting in c2 100
nREPL-worker-20 : Transforming 100
nREPL-worker-20 : Putting in c1 1
async-dispatch-35 : Getting from c2 100
async-dispatch-34 : Transforming 1 <---- In this case is run in the reading side
async-dispatch-34 : Getting from c1 1
nREPL-worker-20 : Putting in c2 100
nREPL-worker-20 : Transforming 100
async-dispatch-37 : Getting from c2 100
async-dispatch-36 : Getting from c1 1
nREPL-worker-20 : Putting in c1 1