Back

elixir - 10. 进程Process, spawn , spawn_link

发布时间: 2019-03-04 01:23:00

process 在elixir中是基本单位。 根据process, Elixir 实现了多进程的功能。 

Elixir中,Process 这个概念跟其他的编程语言不太一样, 甚至比其他语言的Thread还要轻量级。

> p = spawn fn -> 1 + 2 end
#PID<0.199.0>

spawn 会根据传入的函数生成一个 process .

Process.alive?(p)
false

说明该进程已经结束了。 

在iex下, 

>Process.alive?(self())    返回 true , 说明该进程仍然在工作中。

> self()      

#PID<0.219.0>

> send self(), { :hello, "world"}

iex(77)> receive do 
...(77)> {:hello, msg} -> msg
...(77)> {:world, msg } -> "won't match"
...(77)> end

# => "world" 

flush() : 打印 mailbox中所有的内容(打印之后,该内容就不见了)

> send self(), 'hello'
> send self(), 'siwei'
> flush()
'hello'
'siwei'
:ok

Spawn

spawn link 

如果我们让某个process 挂掉,可以这样:

iex(6)> spawn fn -> raise "dang~ " end
#PID<0.112.0>
iex(7)> 
11:32:02.149 [error] Process #PID<0.112.0> raised an exception
** (RuntimeError) dang~ 
    (stdlib) erl_eval.erl:678: :erl_eval.do_apply/6

我们可以使用 spawn_link ,来让这个 process 的parent挂掉

iex(8)> spawn_link fn -> raise "duang ~~ make parent down" end
** (EXIT from #PID<0.103.0>) shell process exited with reason: an exception was raised:
    ** (RuntimeError) duang ~~ make parent down
        (stdlib) erl_eval.erl:678: :erl_eval.do_apply/6

11:32:49.849 [error] Process #PID<0.116.0> raised an exception
** (RuntimeError) duang ~~ make parent down
    (stdlib) erl_eval.erl:678: :erl_eval.do_apply/6
 
Interactive Elixir (1.8.1) - press Ctrl+C to exit (type h() ENTER for help)

Task

该class 比 spawn的使用要“高级”很多, spawn是底层的方法。 Task提供了更强的可读性。

> Task.start fn -> raise "dang ~ " end
{:ok, #PID<0.138.0>}
iex(7)> 
11:41:05.379 [error] Task #PID<0.138.0> started from #PID<0.131.0> terminating
** (RuntimeError) dang ~ 
    (stdlib) erl_eval.erl:678: :erl_eval.do_apply/6
    (elixir) lib/task/supervised.ex:90: Task.Supervised.invoke_mfa/2
    (stdlib) proc_lib.erl:249: :proc_lib.init_p_do_apply/3
Function: #Function<20.128620087/0 in :erl_eval.expr/5>
    Args: []

Task.start_link 用法跟 Task.start 也一样

Task.start_link fn -> raise "dang ~ " end
{:ok, #PID<0.141.0>}

11:41:29.513 [error] Task #PID<0.141.0> started from #PID<0.131.0> terminating
** (RuntimeError) dang ~ 
    (stdlib) erl_eval.erl:678: :erl_eval.do_apply/6
    (elixir) lib/task/supervised.ex:90: Task.Supervised.invoke_mfa/2
    (stdlib) proc_lib.erl:249: :proc_lib.init_p_do_apply/3
Function: #Function<20.128620087/0 in :erl_eval.expr/5>
    Args: []
** (EXIT from #PID<0.131.0>) shell process exited with reason: an exception was raised:
    ** (RuntimeError) dang ~ 
        (stdlib) erl_eval.erl:678: :erl_eval.do_apply/6
        (elixir) lib/task/supervised.ex:90: Task.Supervised.invoke_mfa/2
        (stdlib) proc_lib.erl:249: :proc_lib.init_p_do_apply/3
        
Interactive Elixir (1.8.1) - press Ctrl+C to exit (type h() ENTER for help)

新建一个文件  kv.exs

# kv.exs:
defmodule KV do
  def start_link do
    Task.start_link(fn -> loop(%{}) end )
  end 

  defp loop(map) do
    receive do
      {:get, key , caller} ->
        send caller, Map.get(map, key)
        loop(map)
      {:put, key, value} ->
        loop(Map.put(map, key, value))
    end 
  end 
end

# 然后在iex 中调用:
iex(1)> {:ok, pid} = KV.start_link
{:ok, #PID<0.108.0>}
iex(2)> send pid, {:get, :hello, self()}
{:get, :hello, #PID<0.106.0>}
iex(3)> flush
nil
:ok

# 之前kv, 中是没有内容 的, 现在把内容加进来  
iex> send pid, {:put, :hello, :world}
{:put, :hello, :world}
iex> send pid, {:get, :hello, self()}
{:get, :hello, #PID<0.41.0>}
iex> flush()
:world
:ok

也可以使用 Agent来实现相关的操作

iex(7)> {:ok, pid} = Agent.start_link(fn -> %{} end )
{:ok, #PID<0.116.0>}
iex(8)> pid
#PID<0.116.0>
iex(9)> Agent.update(pid, fn map -> Map.put(map, :hello, :world) end )
:ok
iex(10)> Agent.get(pid, fn map -> Map.get(map, :hello) end)

Back