4 ms·
I'll do my best, but it's a bit hard to explain. Basically channels are yet-another synchronization paradigm like locking or shared memory, some people like it
by majke 13y ago
I'll do my best, but it's a bit hard to explain.
Basically channels are yet-another synchronization paradigm like locking or shared memory, some people like it some don't. Channels are an implementation of Hoare's CSP [0].
Channels can be passed around, the same could be said about Lua coroutines. But with channels you get more flexibility:
- you can "block" on many channels at once using the "chanalt" statement. You can "resume" only one lua coroutine at a time.
- channels they can buffer messages (ie: channels can queue several values)
- many coroutines may "send" a value to a channel at the same time, many coroutines may try to "listen" (receive) a value at the same time.
- finally you can pass a channel over a channel
I find channels, as opposed to many other synchronization paradigms, to be composable and generally nice in use.
It's a "better" alternative to synchronization locking and mutable data. But in Lua, of course, there aren't multiple threads so why synchronization is useful? In the same way that coroutines are useful - they allow you to decompose a program into set of smaller programs. The example given by Russ Cox is the Eratosthenes sieve. You can read about it [1] or watch him talking about it [2], finally my implementation following his talk [3].
[0] https://en.wikipedia.org/wiki/Communicating_sequential_processes https://en.wikipedia.org/wiki/Communicating_sequential_proce...
[1] http://swtch.com/~rsc/thread/ http://swtch.com/~rsc/thread/
[2] http://www.youtube.com/watch?feature=player_detailpage&v=hB05UFqOtFA#t=1600s http://www.youtube.com/watch?feature=player_detailpage&v=hB0...
[3] https://github.com/majek/lua-channels/blob/master/sieve.lua https://github.com/majek/lua-channels/blob/master/sieve.lua