Skip to content

Instantly share code, notes, and snippets.

@rcillo
Last active August 29, 2015 14:05
Show Gist options
  • Save rcillo/917c6293432003a4c797 to your computer and use it in GitHub Desktop.
Save rcillo/917c6293432003a4c797 to your computer and use it in GitHub Desktop.
defmodule GoChannel do
def make do
spawn(&GoChannel.server/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 server do
receive do
{ :read, caller } -> receive do
{ :write, val } -> send(caller, { :read, self, val }); server
end
end
end
end
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment