作 w3cschool erlang 的练习
---------
1 -module(tut16). 2 3 -export([start/0, ping/1, pong/0]). 4 5 %% Erlang 注册进程名称 6 7 %% ping 进程必须通过某种途径 获得 pong 进程的进程标识符后 8 %% 才能将消息发送给 pong 进程 9 10 %% Erlang 提供了 为每个进程提供一个名称绑定的机制, 11 %% 这样进程间通信就可以通过进程名来实现, 而不需要知道进程的进程标识符了. 12 %% 为每个进程注册一个名称需要用到内置函数 register : 13 %% register(some_atom, Pid) 14 15 ping(0) -> 16 pong ! finished, 17 io:format("ping finished~n", []); 18 ping(N) -> 19 pong ! {ping, self()}, 20 receive 21 pong -> 22 io:format("Ping received pong~n", []) 23 end, 24 ping(N - 1). 25 26 pong() -> 27 receive 28 finished -> 29 io:format("pong finished~n", []); 30 {ping, Ping_PID} -> 31 io:format("Pong received ping~n", []), 32 Ping_PID ! pong, 33 pong() 34 end. 35 36 start() -> 37 register(pong, spawn(tut16, pong, [])), 38 spawn(tut16, ping, [3]).
--------- THE END ---------