问题
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