Search code examples
clojureclojurescript

Difference between a shared variable and a channel


Apart from facilitating communication between processes, how does using a channel differ from using some form of shared state, an atom for instance?


Solution

  • They are very different:

    • An atom is a wrapper around a value so that future values are derived by function application (and optionally, you can pass a validation function). From the Clojure reference pages: "Atoms are an efficient way to represent some state that will never need to be coordinated with any other, and for which you wish to make synchronous changes".

    • Channels were introduced in a talk that described them using a conveyor belt analogy: you put some stuff on one end, they arrive on the consumer end. You can go and grab something from the channel if there is something on it (or wait until an item arrives).

    You could use a sequence in an atom as a substitute of a channel, but it would be a poor replacement, most likely to require consumers of how to queue, consume, etc.