Introducción

Besides addressing a process by using its pid, there are also BIFs for registering a process under a name. The name must be an atom and is automatically unregistered if the process terminates:

register(Name, Pid) Associates the name Name, an atom, with the process Pid.
registered() Returns a list of names which have been registered using register/2.
whereis(Name) Returns the pid registered under Name, or undefined if the name is not registered.

pp2@nereida:~/Lerlang$ cat -n area_server0.erl
     1  -module(area_server0).
     2  -export([loop/0]).
     3  %% ~~~~~~
     4
     5  loop() ->
     6      receive
     7        {rectangle, Width, Ht} ->
     8          io:format("Area of rectangle is ~p~n", [Width*Ht]),
     9          loop();
    10        {circle, R} ->
    11          io:format("Area of circle is ~p~n", [3.14159*R*R]),
    12          loop();
    13        Other ->
    14          io:format("I don't know what the area of a ~p is ~n", [Other]),
    15          loop()
    16      end.

3> c(area_server0).
{ok,area_server0}

4> Pid = spawn(fun area_server0:loop/0 end).
* 2: syntax error before: 'end'
4> Pid = spawn(fun area_server0:loop/0).
<0.45.0>
5> register(area, Pid).
true
6> area! { rectangle, 4, 5}
6> .
Area of rectangle is 20
{rectangle,4,5}

Un Reloj

pp2@nereida:~/Lerlang$ erl
Erlang (BEAM) emulator version 5.6.5 [source] [64-bit] [smp:8] [async-threads:0] [hipe] [kernel-poll:false]

Eshell V5.6.5  (abort with ^G)
1> c(clock).
{ok,clock}
2> clock:start(5000, fun() -> io:format("TICK ~p~n", [erlang:now()) end).
* 1: syntax error before: ')'
2> clock:start(5000, fun() -> io:format("TICK ~p~n", [erlang:now()]) end).
true
TICK {1259,174993,316298}
TICK {1259,174998,320447}
TICK {1259,175003,325772}
TICK {1259,175008,330987}
TICK {1259,175013,332715}
3> clock:stop().
stop
4>
pp2@nereida:~/Lerlang$ cat -n clock.erl
     1  -module(clock).
     2  -export([start/2, stop/0]).
     3
     4  start(Time, Fun) ->
     5      register(clock, spawn(fun() -> tick(Time, Fun) end))
     6  .
     7
     8  stop() -> clock! stop.
     9
    10  tick(Time, Fun) ->
    11      receive
    12          stop -> void
    13      after Time -> Fun(), tick(Time, Fun)
    14      end
    15  .



Subsecciones
Casiano Rodríguez León
Licencia de Creative Commons
Programación Distribuida y Mejora del Rendimiento
por Casiano Rodríguez León is licensed under a Creative Commons Reconocimiento 3.0 Unported License.

Permissions beyond the scope of this license may be available at http://campusvirtual.ull.es/ocw/course/view.php?id=44.
2012-06-19