Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Clojure (core.async) what's the difference between alts and alt?

Tags:

I can't figure out the difference between:

alts! 

and

alt! 

in Clojure's core.async.

like image 625
procr Avatar asked Feb 28 '14 03:02

procr


People also ask

What is the difference between go and Clojure?

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.

How can I compare go and core async?

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.

What are the blocking and non-blocking operations on channels in Clojure?

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.

What happens to the other channels when you use ALTs?

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.


1 Answers

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.

like image 175
Michał Marczyk Avatar answered Sep 30 '22 06:09

Michał Marczyk