In Go Concurrency Patterns talk, Google I/O 2012, presenter Rob Pike demos some great concurrency features from Go, like channels and Go routines, and how it can be used to build fast, replicated and robust software.

Concurrency patterns is a very interesting topic but there was one statement in special that got me thinking:

“The models are equivalent but express things differently.”

This is about the distinction between Go channels and its cousin Erlang messages passing approach to communicating between processes.

Implementing Go channels with Elixir processes and messages

Before discovering that it has been done before, I wrote some simple Elixir code to play with the theoretical equivalence between those two models.

Notice that this implementation is not meant to be complete, nor efficient and is not recommended for production software. Don’t do it at home.

defmodule GoChannel do def make do spawn(&GoChannel.loop/0) end def write(channel, val) do send(channel, { :write, val}) end def read(channel) do send(channel, { :read, self }) receive do { :read, channel, val} -> val end end def loop do receive do { :read, caller } -> receive do { :write, val } -> send(caller, { :read, self, val }); loop end end end end

Some tests

defmodule GoChannelTest do use ExUnit.Case test "write and read to a channel" do channel = GoChannel.make GoChannel.write(channel, 'hello') assert GoChannel.read(channel) == 'hello' end test "write and read preserves order" do channel = GoChannel.make GoChannel.write(channel, 'hello') GoChannel.write(channel, 'world') assert GoChannel.read(channel) == 'hello' assert GoChannel.read(channel) == 'world' end end

This pseudo channel implementation relies on a combination of messages between processes to simulate the original FIFO behaviour of channels.

The same way one could pass a channel as parameter to other functions, since it’s a first-class citizen, we could pass the result of GoChannel.make , since it’s a PID , which in turn is a first-class citizen in Elixir.

Back to concurrency patterns

The first pattern demonstrated in Rob’s talk was fanIn , where two channels were combined into a single one.