I can't figure out the difference between:
alts!
and
alt!
in Clojure's core.async.
The clojure code looks quite similar (besides being a lisp) to the Go code. The main difference is we use the (go ...) macro to spawn a go block. While goroutines and go blocks are slightly interesting in isolation, they become much more powerful when combined with channels.
Update: To avoid having to install core.async locally, you can add the following line to your project.clj (thanks weavejester): We’re all set to start comparing Go and core.async. Both core.async and Go provide a facility for spawning “lightweight threads”. In core.async, this is handled via go blocks. In Go, we use goroutines.
Note: Clojure core.async provides two sets of operations on channels. The blocking operations are for use with native threads and the non-blocking operations are for use with go blocks. In this post, I’ll be focusing on the non-blocking operations used with go blocks but I’ll briefly mention the blocking versions.
The other channels are still available if you want to take their values and do something with them. All alts!! does is take a value from the first channel to have a value; it doesn’t touch the other channels. One cool aspect of alts!! is that you can give it a timeout channel, which waits the specified number of milliseconds and then closes.
alts!
is a function that accepts a vector of channels to take from and/or channels with values to be put on them (in the form of doubleton vectors: [c v]
). The vector may be dynamically constructed; the code calling alts!
may not know how many channels it'll be choosing among (and indeed that number need not be constant across invocations).
alt!
is a convenience macro which basically acts as a cross between cond
and alts!
. Here the number of "ports" (channels or channel+value pairs) must be known statically, but in practice this is quite often the case and the cond
-like syntax is very clear.
alt!
expands to a somewhat elaborate expression using alts!
; apart from the syntactic convenience, it offers no extra functionality.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With