来自 :
- -module(tut15).
-
-export([start/0, ping/2, pong/0]).
-
-
ping(0, Pong_PID) ->
-
Pong_PID ! finished,
-
io:format("ping finished~n", []);
-
ping(N, Pong_PID) ->
-
Pong_PID ! {ping, self()},
-
receive
-
pong ->
-
io:format("Ping received pong~n", [])
-
end,
-
ping(N - 1, Pong_PID).
-
-
-
pong() ->
-
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(tut15, pong, []),
-
spawn(tut15, ping, [3, Pong_PID]).
首先理解为递归,上面的代码 严格按 匹配模式来运行;遇到 receive 原语会拥塞;
ping > Pong received ping
pong > Ping received pong
ping N-1
ping > Pong received ping
pong > Ping received pong
ping N-1-1
ping > Pong received ping
pong > Ping received pong
ping N-1-1 (触发 ping
(0
, Pong_PID
) )
ping > ping finished
Pong finished
阅读(1157) | 评论(0) | 转发(0) |