【问题标题】:How are transducers executed in core.async channels?转换器如何在 core.async 通道中执行?
【发布时间】:2016-01-18 05:32:46
【问题描述】:

当把频道变成这样的频道时:

(chan 10 tx)

如果我创建了 10 个这样的通道,然后同时向所有通道发送消息,传感器将如何执行。它们是并发运行还是在一个线程上运行?

【问题讨论】:

    标签: clojure clojurescript core.async


    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-07-04
      • 1970-01-01
      • 2014-01-22
      • 2015-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多