Last active
August 29, 2015 14:05
-
-
Save rcillo/917c6293432003a4c797 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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