请大神解释一段Erlang 进程通信代码
我想知道这段程序是按什么顺序执行的呢? 为什么会先输出 Ping received pong 呢?可以详解么?
-module(process1).
-export([start/0, ping/2,pong/0]).
%%程序外部执行调用start()函数
%%返回<0,46,0>
%%然后执行pong()
ping(0,Pong_PID) ->
Pong_PID ! finished,
io:format("ping finished~n",[]);
ping(N,Pong_PID) ->
Pong_PID ! {ping,self()}, %% self()返回当前在运行的进程id
receive
pong ->
io:format("Ping received pong~n",[])
end,
ping(N - 1 , Pong_PID).
pong() ->
receive %%receive构造用于允许进程等待来自其他进程的消息
finished -> %%用于模式匹配,匹配成功进行输出
io:format("Pong finished~n",[]);
{ping , Ping_PID} ->
io:format("Pong received ping~n",[]),
Ping_PID ! pong,
pong()
end.
start() ->
Pong_PID=spawn(process1,pong,[]), %%建立一个pong进程
spawn(process1,ping,[3,Pong_PID]). %%建立一个ping进程