首页 > Erlang快速入门 > 4.3 Erlang快速入门之注册进程名称
2013
11-03

4.3 Erlang快速入门之注册进程名称

Erlang注册进程名称
在上面的例子中,我们首先创建了“pong”,然后在启动“ping”之前给“pong”一个唯一标识符。某些时候“ping”必须直到“pong”的标识符才能够发送消息给它。某些时候进程需要知道对方的情况,但是进程之间又是完全独立的。所以为了解决分配pid和互相识别的困难,Erlang提供了一个赋予进程以名字的机制,我们能够通过使用进程名字来代替pid的使用。这必须使用到内建函数register:
register(some_atom, Pid)
我们现在重写我们的ping pong例子,我们将赋予ping和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中,
register(pong, spawn(tut16, pong, [])),
将名称“pong”赋予了进程“pong”。在进程“ping”中我们可以直接使用pong来对它发送消息:
pong ! {ping, self()},
所以这里的ping/2可以简化为ping/1,不再使用参数Pong_PID。


4.3 Erlang快速入门之注册进程名称》有 1 条评论

  1. 游客 说:

    为什么提示第9行错误?syntax error before: pong

留下一个回复

你的email不会被公开。