clojure.core.async - 使用>!和<!在函数调用中

fyq*_*h95 4 asynchronous clojure

我希望能够从go-block调用函数时停放.使用>!<!不按预期工作.

这将适当地停放.

(go (<! (chan)))
Run Code Online (Sandbox Code Playgroud)

但是,如果我们有函数调用,

(defn f [c] (<! c))
(go (f (chan)))
Run Code Online (Sandbox Code Playgroud)

<!不被去块来拆分,因为它是在一个函数.这有什么替代方案吗?最近一个我能想到的是写一个宏f,而不是一个功能-是否有替代作用,而不是<!>!我可以用于此用途?

Ole*_*Cat 6

这是一个已知的限制core.async.go宏只重写传递的s-expression,它不能真正"看"内部函数体.

我建议如下重写你的例子(如果你想使用停车场和获取):

(defn f [c] (go (<! c)))
(go (<! (f (chan))))
Run Code Online (Sandbox Code Playgroud)

此外,总是有可能使用阻塞put和take(<!!,>!!).

> (time (dotimes [n 100000] (<!! (go (<! (let [ch (chan)] (put! ch 1) ch))))))
"Elapsed time: 1432.751927 msecs"
nil

> (time (dotimes [n 100000] (<!! (go (<! (go (<! (let [ch (chan)] (put! ch 1) ch))))))))
"Elapsed time: 1828.132637 msecs"
nil
Run Code Online (Sandbox Code Playgroud)

根据基准测试,初始方法(如果已得到支持core.async)应该比建议的解决方法快30%.