Created
July 18, 2019 19:39
-
-
Save Ljzn/b95803dee3ae81c35afb425abd9ade70 to your computer and use it in GitHub Desktop.
Concurrent Rainbow 7 个进程相互之间并不通信, 它们只和一个中心通信, 最后 7 个进程都拥有了各自独特的颜色
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 Rainbow do | |
@moduledoc """ | |
Documentation for Rainbow. | |
""" | |
@colors ~w(赤 橙 黄 绿 青 蓝 紫) | |
def start do | |
node = spawn(fn -> | |
loop([]) | |
end) | |
for _ <- 1..7 do | |
spawn(fn -> draw(node, @colors) end) | |
end | |
end | |
def draw(node, [color|colors]) do | |
case post(node, color) do | |
:ok -> IO.inspect({self(), color}) | |
:error -> draw(node, colors) | |
end | |
end | |
def post(node, color) do | |
send(node, {:color, color, self()}) | |
receive do | |
{:resp, resp} -> | |
resp | |
end | |
end | |
defp loop(state) do | |
receive do | |
{:color, color, pid} -> | |
if color in state do | |
send(pid, {:resp, :error}) | |
loop(state) | |
else | |
send(pid, {:resp, :ok}) | |
loop([color|state]) | |
end | |
end | |
end | |
end |
Author
Ljzn
commented
Jul 18, 2019
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment