Why do core.async go blocks return a channel?

允我心安 提交于 2019-12-24 01:01:40

问题


I understand that 'go blocks' (whether go or go-loop or possibly other constructs) return a channel. 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.


回答1:


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. Alternatively, I can preform blocking reads on the channel to guarantee when the execution of the go-block has completed.

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.



来源:https://stackoverflow.com/questions/36236869/why-do-core-async-go-blocks-return-a-channel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!