Download Erlang/OTP System Documentation

Transcript
4.3 Concurrent Programming
A tuple {registered_name,node_name} is used instead of just the registered_name.
In the previous example, "ping" and "pong" were started from the shells of two separate Erlang nodes. spawn can
also be used to start processes in other nodes.
The next example is the ping pong program, yet again, but this time "ping" is started in another node:
-module(tut18).
-export([start/1,
ping/2, pong/0]).
ping(0, Pong_Node) ->
{pong, Pong_Node} ! finished,
io:format("ping finished~n", []);
ping(N, Pong_Node) ->
{pong, Pong_Node} ! {ping, self()},
receive
pong ->
io:format("Ping received pong~n", [])
end,
ping(N - 1, Pong_Node).
pong() ->
receive
finished ->
io:format("Pong finished~n", []);
{ping, Ping_PID} ->
io:format("Pong received ping~n", []),
Ping_PID ! pong,
pong()
end.
start(Ping_Node) ->
register(pong, spawn(tut18, pong, [])),
spawn(Ping_Node, tut18, ping, [3, node()]).
Assuming an Erlang system called ping (but not the "ping" process) has already been started on kosken, then on gollum
this is done:
(pong@gollum)1> tut18:start(ping@kosken).
<3934.39.0>
Pong received ping
Ping received pong
Pong received ping
Ping received pong
Pong received ping
Ping received pong
Pong finished
ping finished
Notice that all the output is received on gollum. This is because the I/O system finds out where the process is spawned
from and sends all output there.
4.3.5 A Larger Example
Now for a larger example with a simple "messenger". The messenger is a program that allows users to log in on
different nodes and send simple messages to each other.
104 | Ericsson AB. All Rights Reserved.: Erlang/OTP System Documentation