LoginSignup
14
1

More than 1 year has passed since last update.

簡単Elixirシリーズ ~ プロセスを知ろう③ ~

Posted at

簡単Elixirシリーズ

~ プロセスを知ろう③ ~

この記事は「Elixir Advent Calendar 2022」24日目の記事です
東京にいるけどfukuokaexのYOSUKEです。

簡単 Elixirシリーズでは小ネタをサクッと書いていこう。というコンセプトで作っていきます。

今回は、プロセスについて公式ドキュメントを見ながらサクッと解説の第3段です。

さて、前回の記事の続きものです、ちなみに前回の記事はこちらです。

さて、前回の例ではプロセスを継続的に終了しないようにコードを書き換えました。
今度は、さらにコードを変えて、状態を維持するように変換していきます。


defmodule MyProcess do
  def await_receive_msg(msg_received \\ []) do
    IO.puts "プロセス #{inspect(self())}, メッセージ待ち中"
    receive do
      {x, y} = msg -> IO.puts "x + y = #{x + y}"
              [msg | msg_received ]
              |> IO.inspect(label: "メッセージ: ")
              |> await_receive_msg()
      "Quit" = msg -> IO.puts "計算をやめます。"
              [msg | msg_received ]
              |> IO.inspect(label: "メッセージ: ")
              |> await_receive_msg()
      msg -> IO.puts "なんか別のメッセージが送られてきました"
              [msg | msg_received ]
              |> IO.inspect(label: "メッセージ: ")
              |> await_receive_msg()
    end
  end
end

これで準び完了です。
早速、実行してみましょう。 メッセージを送った情報が蓄積されて行く様子がわかります。

iex()> pid = spawn(MyProcess, :await_receive_msg, []) 
プロセス #PID<0.152.0>, メッセージ待ち中
#PID<0.152.0>
iex()> send(pid, [1,2])                              
なんか別のメッセージが送られてきました
[1, 2]
メッセージ: : [[1, 2]]
プロセス #PID<0.152.0>, メッセージ待ち中
iex()> send(pid, {1,2})
x + y = 3
{1, 2}
メッセージ: : [{1, 2}, [1, 2]]
プロセス #PID<0.152.0>, メッセージ待ち中
iex()> send(pid, {4,2})
x + y = 6
{4, 2}
メッセージ: : [{4, 2}, {1, 2}, [1, 2]]
プロセス #PID<0.152.0>, メッセージ待ち中
iex()> send(pid, "Quit")
計算をやめます。
"Quit"
メッセージ: : ["Quit", {4, 2}, {1, 2}, [1, 2]]
プロセス #PID<0.152.0>, メッセージ待ち中

これで、プロセスが状態を保持しながら継続する処理ができました。
これって、LiveView になんだか似てますね。

14
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
1