W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
上面的例子中,因為 “Pong” 在 “ping” 進程開始前已經(jīng)創(chuàng)建完成,所以才能將 “pong” 進程的進程標識符作為參數(shù)傳遞給進程 “ping”。這也就說,“ping” 進程必須通過某種途徑獲得 “pong” 進程的進程標識符后才能將消息發(fā)送 “pong” 進程。然而,某些情況下,進程需要相互獨立地啟動,而這些進程之間又要求知道彼此的進程標識符,前面提到的這種方式就不能滿足要求了。因此,Erlang 提供了為每個進程提供一個名稱綁定的機制,這樣進程間通信就可以通過進程名來實現(xiàn),而不需要知道進程的進程標識符了。為每個進程注冊一個名稱需要用到內(nèi)置函數(shù) register:
register(some_atom, Pid)
接下來,讓我們一起上面的 ping pong 示例程序。這一次,我們?yōu)?“pong” 進程賦予了一名進程名稱 pong:
-module(tut16).
-export([start/0, ping/1, pong/0]).
ping(0) ->
pong ! finished,
io:format("ping finished~n", []);
ping(N) ->
pong ! {ping, self()},
receive
pong ->
io:format("Ping received pong~n", [])
end,
ping(N - 1).
pong() ->
receive
finished ->
io:format("Pong finished~n", []);
{ping, Ping_PID} ->
io:format("Pong received ping~n", []),
Ping_PID ! pong,
pong()
end.
start() ->
register(pong, spawn(tut16, pong, [])),
spawn(tut16, ping, [3]).
2> c(tut16).
{ok, tut16}
3> tut16:start().
<0.38.0>
Pong received ping
Ping received pong
Pong received ping
Ping received pong
Pong received ping
Ping received pong
ping finished
Pong finished
start/0 函數(shù)如下:
register(pong, spawn(tut16, pong, [])),
創(chuàng)建 “pong” 進程的同時還賦予了它一個名稱 pong。在 “ping” 進程中,通過如下的形式發(fā)送消息:
pong ! {ping, self()},
ping/2 變成了 ping/1。這是因為不再需要參數(shù) Pong_PID 了。
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: