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.