简体   繁体   English

为什么core.async go块返回一个通道?

[英]Why do core.async go blocks return a channel?

I understand that 'go blocks' (whether go or go-loop or possibly other constructs) return a channel. 我了解“执行块”(无论是执行go还是go-loop或其他构造)都返回一个通道。 However I have never understood this channel's purpose. 但是,我从未理解过该渠道的目的。 I'd like to know how to use it. 我想知道如何使用它。 Perhaps I'm creating extra channels when I don't need to be. 也许当我不需要时,我会创建更多的渠道。

I use the return channel of a go -block as a handle that I can pass to another function (not just a macro) which wants to synchronize with the completion of the go -block. 我使用go -block的返回通道作为句柄,可以将其传递给另一个函数(不仅仅是宏),该函数希望与go -block的完成同步。 Alternatively, I can preform blocking reads on the channel to guarantee when the execution of the go -block has completed. 另外,我可以在通道上执行阻塞读取,以确保go -block的执行何时完成。

Here is a simple example (not meant to be used for any production code to compute sum) that does a two-way parallelization: 这是一个简单的示例(并不打算用于任何生产代码来计算总和),它执行双向并行化:

(defn par-sum [coll]
  (let [half-n (/ (count coll) 2)
        [left right] (split-at half-n coll)
        left-sum-chan (async/go (core/reduce + 0 left))
        right-sum (core/reduce + 0 right)
        left-sum (async/<!! left-sum-chan)]
    (+ left-sum right-sum)))

In this example, we compute the left and right sums in parallel. 在此示例中,我们并行计算左右总和。 Since we need the left sum to compute the overall sum, we have to wait on the result and retrieve the result of the go -block. 由于我们需要剩余的总和来计算总和,因此我们必须等待结果并检索go -block的结果。

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

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