Skip to content

Instantly share code, notes, and snippets.

@niku
Last active September 10, 2015 22:07
Show Gist options
  • Save niku/5796caa4aec4f9edd438 to your computer and use it in GitHub Desktop.
Save niku/5796caa4aec4f9edd438 to your computer and use it in GitHub Desktop.
Consumer まちまーす(list の長さ 0)
Producer 0 計算時間: 1129ms
Producer 1 計算時間: 776ms
Producer 2 計算時間: 174ms
Producer 3 計算時間: 909ms
Producer 4 計算時間: 1474ms
Producer 5 計算時間: 1328ms
Producer 2 送りまーす
Consumer 2 受けましたー
Consumer まちまーす(list の長さ 1)
Producer 1 送りまーす
Consumer 1 受けましたー
Consumer ペアは 2 と 1 です
Consumer まちまーす(list の長さ 0)
Producer 3 送りまーす
Consumer 3 受けましたー
Consumer まちまーす(list の長さ 1)
Producer 0 送りまーす
Consumer 0 受けましたー
Consumer ペアは 3 と 0 です
Consumer まちまーす(list の長さ 0)
Producer 5 送りまーす
Consumer 5 受けましたー
Consumer まちまーす(list の長さ 1)
Producer 4 送りまーす
Consumer 4 受けましたー
Consumer ペアは 5 と 4 です
Consumer まちまーす(list の長さ 0)
Consumer 時間切れ
defmodule Producer do
def produce(dest_pid) do
Stream.repeatedly(&:random.uniform/0) # ランダムな値
|> Stream.with_index # n 番目
|> Stream.each(fn {random, index} -> # {ランダムな値, n 番目}
spawn fn -> # 別プロセスを作る
sleeptime = trunc(random * 2 * 1000)
IO.puts "Producer #{index} 計算時間: #{sleeptime}ms"
:timer.sleep(sleeptime) # 0-2 秒待って(重い処理のつもり)
IO.puts "Producer #{index} 送りまーす"
send(dest_pid, index) # dest_pid に結果を送る
end
end)
end
end
defmodule Consumer do
def consume(list) do
IO.puts "Consumer まちまーす(list の長さ #{length list})"
receive do
x -> # x を受けとったら
IO.puts "Consumer #{x} 受けましたー"
if length(list) == 1 do
IO.puts "Consumer ペアは #{hd(list)} と #{x} です"
consume([])
else
consume([x])
end
after
5000 -> # 5 秒待ったら打ち切る
IO.puts "Consumer 時間切れ"
end
end
end
:random.seed(:os.timestamp) # ランダムな値を生成するための処理
# (おまじない)
Enum.take(Producer.produce(self()), 6) # 自分のプロセス self() に 6 個作って送る
Consumer.consume([]) # メッセージが送られてくるのを待つ
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment