Skip to content

Instantly share code, notes, and snippets.

@Ljzn
Created July 18, 2019 19:39
Show Gist options
  • Save Ljzn/b95803dee3ae81c35afb425abd9ade70 to your computer and use it in GitHub Desktop.
Save Ljzn/b95803dee3ae81c35afb425abd9ade70 to your computer and use it in GitHub Desktop.
Concurrent Rainbow 7 个进程相互之间并不通信, 它们只和一个中心通信, 最后 7 个进程都拥有了各自独特的颜色
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
@Ljzn
Copy link
Author

Ljzn commented Jul 18, 2019

iex(1)> Rainbow.start
[#PID<0.143.0>, #PID<0.144.0>, #PID<0.145.0>, #PID<0.146.0>, #PID<0.147.0>,
 #PID<0.148.0>, #PID<0.149.0>]
{#PID<0.144.0>, "橙"}
{#PID<0.145.0>, "黄"}
{#PID<0.146.0>, "绿"}
{#PID<0.147.0>, "青"}
{#PID<0.148.0>, "蓝"}
{#PID<0.149.0>, "紫"}
{#PID<0.143.0>, "赤"}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment