Sophie

Sophie

distrib > Mageia > 6 > x86_64 > media > core-updates > by-pkgid > eb1ec8bb814fe4d749258d46ae8ea988 > files > 62

erlang-doc-18.3.2-9.1.mga6.noarch.rpm

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html xmlns:fn="http://www.w3.org/2005/02/xpath-functions">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="../otp_doc.css" type="text/css">
<title>Erlang -- Concurrent Programming</title>
</head>
<body bgcolor="white" text="#000000" link="#0000ff" vlink="#ff00ff" alink="#ff0000"><div id="container">
<script id="js" type="text/javascript" language="JavaScript" src="../js/flipmenu/flipmenu.js"></script><script id="js2" type="text/javascript" src="../js/erlresolvelinks.js"></script><script language="JavaScript" type="text/javascript">
            <!--
              function getWinHeight() {
                var myHeight = 0;
                if( typeof( window.innerHeight ) == 'number' ) {
                  //Non-IE
                  myHeight = window.innerHeight;
                } else if( document.documentElement && ( document.documentElement.clientWidth ||
                                                         document.documentElement.clientHeight ) ) {
                  //IE 6+ in 'standards compliant mode'
                  myHeight = document.documentElement.clientHeight;
                } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
                  //IE 4 compatible
                  myHeight = document.body.clientHeight;
                }
                return myHeight;
              }

              function setscrollpos() {
                var objf=document.getElementById('loadscrollpos');
                 document.getElementById("leftnav").scrollTop = objf.offsetTop - getWinHeight()/2;
              }

              function addEvent(obj, evType, fn){
                if (obj.addEventListener){
                obj.addEventListener(evType, fn, true);
                return true;
              } else if (obj.attachEvent){
                var r = obj.attachEvent("on"+evType, fn);
                return r;
              } else {
                return false;
              }
             }

             addEvent(window, 'load', setscrollpos);

             //--></script><div id="leftnav"><div class="innertube">
<img alt="Erlang logo" src="../erlang-logo.png"><br><small><a href="users_guide.html">User's Guide</a><br><a href="../pdf/otp-system-documentation-7.3.1.pdf">PDF</a><br><a href="../index.html">Top</a></small><p><strong>Getting Started with Erlang</strong><br><strong>User's Guide</strong><br><small>Version 7.3.1</small></p>
<br><a href="javascript:openAllFlips()">Expand All</a><br><a href="javascript:closeAllFlips()">Contract All</a><p><small><strong>Chapters</strong></small></p>
<ul class="flipMenu" imagepath="../js/flipmenu">
<li id="no" title="Introduction" expanded="false">Introduction<ul>
<li><a href="intro.html">
              Top of chapter
            </a></li>
<li title="Prerequisites"><a href="intro.html#idp281230204">Prerequisites</a></li>
<li title="Omitted Topics"><a href="intro.html#idp281296740">Omitted Topics</a></li>
</ul>
</li>
<li id="no" title="Sequential Programming" expanded="false">Sequential Programming<ul>
<li><a href="seq_prog.html">
              Top of chapter
            </a></li>
<li title="The Erlang Shell"><a href="seq_prog.html#idp280867116">The Erlang Shell</a></li>
<li title="Modules and Functions"><a href="seq_prog.html#idp281301196">Modules and Functions</a></li>
<li title="Atoms"><a href="seq_prog.html#idp280980780">Atoms</a></li>
<li title="Tuples"><a href="seq_prog.html#idp281373380">Tuples</a></li>
<li title="Lists"><a href="seq_prog.html#idp280988244">Lists</a></li>
<li title="Maps"><a href="seq_prog.html#idp281292780">Maps</a></li>
<li title="Standard Modules and Manual Pages"><a href="seq_prog.html#idp281256484">Standard Modules and Manual Pages</a></li>
<li title="Writing Output to a Terminal"><a href="seq_prog.html#idp281225364">Writing Output to a Terminal</a></li>
<li title="A Larger Example"><a href="seq_prog.html#idp280901828">A Larger Example</a></li>
<li title="Matching, Guards, and Scope of Variables"><a href="seq_prog.html#idp280991068">Matching, Guards, and Scope of Variables</a></li>
<li title="More About Lists"><a href="seq_prog.html#idp281562988">More About Lists</a></li>
<li title="If and Case"><a href="seq_prog.html#idp281581828">If and Case</a></li>
<li title="Built-In Functions (BIFs)"><a href="seq_prog.html#idp281597868">Built-In Functions (BIFs)</a></li>
<li title="Higher-Order Functions (Funs)"><a href="seq_prog.html#idp281610788">Higher-Order Functions (Funs)</a></li>
</ul>
</li>
<li id="loadscrollpos" title="Concurrent Programming" expanded="true">Concurrent Programming<ul>
<li><a href="conc_prog.html">
              Top of chapter
            </a></li>
<li title="Processes"><a href="conc_prog.html#idp281631836">Processes</a></li>
<li title="Message Passing"><a href="conc_prog.html#idp281641636">Message Passing</a></li>
<li title="Registered Process Names"><a href="conc_prog.html#idp281664988">Registered Process Names</a></li>
<li title="Distributed Programming"><a href="conc_prog.html#idp281671924">Distributed Programming</a></li>
<li title="A Larger Example"><a href="conc_prog.html#idp281692036">A Larger Example</a></li>
</ul>
</li>
<li id="no" title="Robustness" expanded="false">Robustness<ul>
<li><a href="robustness.html">
              Top of chapter
            </a></li>
<li title="Time-outs"><a href="robustness.html#idp281742052">Time-outs</a></li>
<li title="Error Handling"><a href="robustness.html#idp281750788">Error Handling</a></li>
<li title="The Larger Example with Robustness Added"><a href="robustness.html#idp281765524">The Larger Example with Robustness Added</a></li>
</ul>
</li>
<li id="no" title="Records and Macros" expanded="false">Records and Macros<ul>
<li><a href="record_macros.html">
              Top of chapter
            </a></li>
<li title="The Larger Example Divided into Several Files"><a href="record_macros.html#idp281781356">The Larger Example Divided into Several Files</a></li>
<li title="Header Files"><a href="record_macros.html#idp281794484">Header Files</a></li>
<li title="Records"><a href="record_macros.html#idp281797356">Records</a></li>
<li title="Macros"><a href="record_macros.html#idp281803804">Macros</a></li>
</ul>
</li>
</ul>
</div></div>
<div id="content">
<div class="innertube">
<h1>3 Concurrent Programming</h1>
  

  <a name="Distributed%20Programming"></a>
  <h3><a name="idp281631836">3.1 
        Processes</a></h3>
    
    <p>One of the main reasons for using Erlang instead of other
      functional languages is Erlang's ability to handle concurrency
      and distributed programming. By concurrency is meant programs
      that can handle several threads of execution at the same time.
      For example, modern operating systems allow you to use a
      word processor, a spreadsheet, a mail client, and a print job all
      running at the same time. Each processor (CPU) in
      the system is probably only handling one thread (or job) at a
      time, but it swaps between the jobs at such a rate that it gives
      the illusion of running them all at the same time. It is easy to
      create parallel threads of execution in an Erlang program and
      to allow these threads to communicate with each other. In
      Erlang, each thread of execution is called a <strong>process</strong>.</p>
    <p>(Aside: the term "process" is usually used when the threads of
      execution share no data with each other and the term "thread"
      when they share data in some way. Threads of execution in Erlang
      share no data, that is why they are called processes).</p>
    <p>The Erlang BIF <span class="code">spawn</span> is used to create a new process:
      <span class="code">spawn(Module, Exported_Function, List of Arguments)</span>.
      Consider the following module:</p>
    <div class="example"><pre>
-module(tut14).

-export([start/0, say_something/2]).

say_something(What, 0) -&gt;
    done;
say_something(What, Times) -&gt;
    io:format("~p~n", [What]),
    say_something(What, Times - 1).

start() -&gt;
    spawn(tut14, say_something, [hello, 3]),
    spawn(tut14, say_something, [goodbye, 3]).</pre></div>
    <div class="example"><pre>
5&gt; <span class="bold_code">c(tut14).</span>
{ok,tut14}
6&gt; <span class="bold_code">tut14:say_something(hello, 3).</span>
hello
hello
hello
done</pre></div>
    <p>As shown, the function <span class="code">say_something</span> writes its first
      argument the number of times specified by second argument.
      The function <span class="code">start</span> starts two Erlang processes,
      one that writes "hello" three times and one that writes
      "goodbye" three times. Both processes use the function
      <span class="code">say_something</span>. Notice that a function used in this way by
      <span class="code">spawn</span>, to start a process, must be exported from the module
      (that is, in the <span class="code">-export</span> at the start of the module).</p>
    <div class="example"><pre>
9&gt; <span class="bold_code">tut14:start().</span>
hello
goodbye
&lt;0.63.0&gt;
hello
goodbye
hello
goodbye</pre></div>
    <p>Notice that it did not write "hello" three times and then
      "goodbye" three times. Instead, the first process wrote a "hello",
      the second a "goodbye", the first another "hello" and so forth.
      But where did the &lt;0.63.0&gt; come from? The return value of a
      function is the return value of the last "thing" in
      the function. The last thing in the function <span class="code">start</span> is</p>
    <div class="example"><pre>
spawn(tut14, say_something, [goodbye, 3]).</pre></div>
    <p><span class="code">spawn</span> returns a <strong>process identifier</strong>, or
      <strong>pid</strong>, which uniquely identifies the process. So &lt;0.63.0&gt;
      is the pid of the <span class="code">spawn</span> function call above.
      The next example shows how to use pids.</p>
    <p>Notice also that ~p is used instead of ~w in
      <span class="code">io:format</span>. To quote the manual: "~p Writes the data with
      standard syntax in the same way as ~w, but breaks terms whose
      printed representation is longer than one line into many lines
      and indents each line sensibly. It also tries to detect lists of
      printable characters and to output these as strings".</p>
  

  <h3><a name="idp281641636">3.2 
        Message Passing</a></h3>
    
    <p>In the following example two processes are created and
    they send messages to each other a number of times.</p>
    <div class="example"><pre>
-module(tut15).

-export([start/0, ping/2, pong/0]).

ping(0, Pong_PID) -&gt;
    Pong_PID ! finished,
    io:format("ping finished~n", []);

ping(N, Pong_PID) -&gt;
    Pong_PID ! {ping, self()},
    receive
        pong -&gt;
            io:format("Ping received pong~n", [])
    end,
    ping(N - 1, Pong_PID).

pong() -&gt;
    receive
        finished -&gt;
            io:format("Pong finished~n", []);
        {ping, Ping_PID} -&gt;
            io:format("Pong received ping~n", []),
            Ping_PID ! pong,
            pong()
    end.

start() -&gt;
    Pong_PID = spawn(tut15, pong, []),
    spawn(tut15, ping, [3, Pong_PID]).</pre></div>
    <div class="example"><pre>
1&gt; <span class="bold_code">c(tut15).</span>
{ok,tut15}
2&gt; <span class="bold_code">tut15: start().</span>
&lt;0.36.0&gt;
Pong received ping
Ping received pong
Pong received ping
Ping received pong
Pong received ping
Ping received pong
ping finished
Pong finished</pre></div>
    <p>The function <span class="code">start</span> first creates a process,
      let us call it "pong":</p>
    <div class="example"><pre>
Pong_PID = spawn(tut15, pong, [])</pre></div>
    <p>This process executes <span class="code">tut15:pong()</span>. <span class="code">Pong_PID</span> is
      the process identity of the "pong" process. The function
      <span class="code">start</span> now creates another process "ping":</p>
    <div class="example"><pre>
spawn(tut15, ping, [3, Pong_PID]),</pre></div>
    <p>This process executes:</p>
    <div class="example"><pre>
tut15:ping(3, Pong_PID)</pre></div>
    <p>&lt;0.36.0&gt; is the return value from the <span class="code">start</span> function.</p>
    <p>The process "pong" now does:</p>
    <div class="example"><pre>
receive
    finished -&gt;
        io:format("Pong finished~n", []);
    {ping, Ping_PID} -&gt;
        io:format("Pong received ping~n", []),
        Ping_PID ! pong,
        pong()
end.</pre></div>
    <p>The <span class="code">receive</span> construct is used to allow processes to wait
      for messages from other processes. It has the following format:</p>
    <div class="example"><pre>
receive
   pattern1 -&gt;
       actions1;
   pattern2 -&gt;
       actions2;
   ....
   patternN
       actionsN
end.</pre></div>
    <p>Notice there is no ";" before the <span class="code">end</span>.</p>
    <p>Messages between Erlang processes are simply valid Erlang terms.
      That is, they can be lists, tuples, integers, atoms, pids,
      and so on.</p>
    <p>Each process has its own input queue for messages it receives.
      New messages received are put at the end of the queue. When a
      process executes a <span class="code">receive</span>, the first message in the queue
      is matched against the first pattern in the <span class="code">receive</span>. If
      this matches, the message is removed from the queue and
      the actions corresponding to the pattern are executed.</p>
    <p>However, if the first pattern does not match, the second pattern
      is tested. If this matches, the message is removed from the queue
      and the actions corresponding to the second pattern are executed.
      If the second pattern does not match, the third is tried and so on
      until there are no more patterns to test. If there are no more
      patterns to test, the first message is kept in the queue and
      the second message is tried instead. If this matches any pattern,
      the appropriate actions are executed and the second message is
      removed from the queue (keeping the first message and any other
      messages in the queue). If the second message does not match,
      the third message is tried, and so on, until the end of
      the queue is reached. If the end of the queue is reached,
      the process blocks
      (stops execution) and waits until a new message is received and
      this procedure is repeated.</p>
    <p>The Erlang implementation is "clever" and minimizes
      the number of times each message is tested against the patterns
      in each <span class="code">receive</span>.</p>
    <p>Now back to the ping pong example.</p>
    <p>"Pong" is waiting for messages. If the atom <span class="code">finished</span> is
      received, "pong" writes "Pong finished" to the output and, as it
      has nothing more to do, terminates. If it receives a message with
      the format:</p>
    <div class="example"><pre>
{ping, Ping_PID}</pre></div>
    <p>it writes "Pong received ping" to the output and sends the atom
      <span class="code">pong</span> to the process "ping":</p>
    <div class="example"><pre>
Ping_PID ! pong</pre></div>
    <p>Notice how the operator "!" is used to send messages. The syntax
      of "!" is:</p>
    <div class="example"><pre>
Pid ! Message</pre></div>
    <p>That is, <span class="code">Message</span> (any Erlang term) is sent to the process
      with identity <span class="code">Pid</span>.</p>
    <p>After sending the message <span class="code">pong</span> to the process "ping",
      "pong" calls the <span class="code">pong</span> function again, which causes it to
      get back to the <span class="code">receive</span> again and wait for another message.</p>
     <p>Now let us look at the process "ping". Recall that it was started
      by executing:</p>
    <div class="example"><pre>
tut15:ping(3, Pong_PID)</pre></div>
    <p>Looking at the function <span class="code">ping/2</span>, the second
      clause of <span class="code">ping/2</span> is executed since the value of the first
      argument is 3 (not 0) (first clause head is
      <span class="code">ping(0,Pong_PID)</span>, second clause head is
      <span class="code">ping(N,Pong_PID)</span>, so <span class="code">N</span> becomes 3).</p>
    <p>The second clause sends a message to "pong":</p>
    <div class="example"><pre>
Pong_PID ! {ping, self()},</pre></div>
    <p><span class="code">self()</span> returns the pid of the process that executes
      <span class="code">self()</span>, in this case the pid of "ping". (Recall the code
      for "pong", this lands up in the variable <span class="code">Ping_PID</span> in
      the <span class="code">receive</span> previously explained.)</p>
    <p>"Ping" now waits for a reply from "pong":</p>
    <div class="example"><pre>
receive
    pong -&gt;
        io:format("Ping received pong~n", [])
end,</pre></div>
    <p>It writes "Ping received pong" when this reply arrives, after
      which "ping" calls the <span class="code">ping</span> function again.</p>
    <div class="example"><pre>
ping(N - 1, Pong_PID)</pre></div>
    <p><span class="code">N-1</span> causes the first argument to be decremented until it
      becomes 0. When this occurs, the first clause of <span class="code">ping/2</span>
      is executed:</p>
    <div class="example"><pre>
ping(0, Pong_PID) -&gt;
    Pong_PID !  finished,
    io:format("ping finished~n", []);</pre></div>
    <p>The atom <span class="code">finished</span> is sent to "pong" (causing it to
      terminate as described above) and "ping finished" is written to
      the output. "Ping" then terminates as it has nothing left
      to do.</p>
  

  <h3><a name="idp281664988">3.3 
        Registered Process Names</a></h3>
    
    <p>In the above example, "pong" was first created to be able
      to give the identity of "pong" when "ping" was started. That is, in
      some way "ping" must be able to know the identity of "pong" to be
      able to send a message to it. Sometimes processes
      which need to know each other's identities are started
      independently of each other. Erlang thus provides a mechanism for
      processes to be given names so that these names can be used as
      identities instead of pids. This is done by using
      the <span class="code">register</span> BIF:</p>
    <div class="example"><pre>
register(some_atom, Pid)</pre></div>
    <p>Let us now rewrite the ping pong example using this and give
      the name <span class="code">pong</span> to the "pong" process:</p>
    <div class="example"><pre>
-module(tut16).

-export([start/0, ping/1, pong/0]).

ping(0) -&gt;
    pong ! finished,
    io:format("ping finished~n", []);

ping(N) -&gt;
    pong ! {ping, self()},
    receive
        pong -&gt;
            io:format("Ping received pong~n", [])
    end,
    ping(N - 1).

pong() -&gt;
    receive
        finished -&gt;
            io:format("Pong finished~n", []);
        {ping, Ping_PID} -&gt;
            io:format("Pong received ping~n", []),
            Ping_PID ! pong,
            pong()
    end.

start() -&gt;
    register(pong, spawn(tut16, pong, [])),
    spawn(tut16, ping, [3]).</pre></div>
    <div class="example"><pre>
2&gt; <span class="bold_code">c(tut16).</span>
{ok, tut16}
3&gt; <span class="bold_code">tut16:start().</span>
&lt;0.38.0&gt;
Pong received ping
Ping received pong
Pong received ping
Ping received pong
Pong received ping
Ping received pong
ping finished
Pong finished</pre></div>
    <p>Here the <span class="code">start/0</span> function,</p>
    <div class="example"><pre>
register(pong, spawn(tut16, pong, [])),</pre></div>
    <p>both spawns the "pong" process and gives it the name <span class="code">pong</span>.
      In the "ping" process, messages can be sent to <span class="code">pong</span> by:</p>
    <div class="example"><pre>
pong ! {ping, self()},</pre></div>
    <p><span class="code">ping/2</span> now becomes <span class="code">ping/1</span> as
      the argument <span class="code">Pong_PID</span> is not needed.</p>
  

  <h3><a name="idp281671924">3.4 
        Distributed Programming</a></h3>
    
    <p>Let us rewrite the ping pong program with "ping" and "pong"
      on different computers. First a few things
      are needed to set up to get this to work. The distributed Erlang
      implementation provides a basic security mechanism to prevent
      unauthorized access to an Erlang system on another computer.
      Erlang systems which talk to each other must have
      the same <strong>magic cookie</strong>. The easiest way to achieve this
      is by having a file called <span class="code">.erlang.cookie</span> in your home
      directory on all machines on which you are going to run
      Erlang systems communicating with each other:
     </p>
      <ul>
	<li>On Windows systems the home directory is the directory
	pointed out by the environment variable $HOME - you may need
        to set this.</li>
        <li> On Linux or UNIX
        you can safely ignore this and simply create a file called
        <span class="code">.erlang.cookie</span> in the directory you get to after executing
        the command <span class="code">cd</span> without any argument.</li>
      </ul>
      <p>The <span class="code">.erlang.cookie</span> file is to contain a line with
      the same atom. For example, on Linux or UNIX, in the OS shell:</p>
    <div class="example"><pre>
$ <span class="bold_code">cd</span>
$ <span class="bold_code">cat &gt; .erlang.cookie</span>
this_is_very_secret
$ <span class="bold_code">chmod 400 .erlang.cookie</span></pre></div>
    <p>The <span class="code">chmod</span> above makes the <span class="code">.erlang.cookie</span> file
      accessible only by the owner of the file. This is a requirement.</p>
    <p>When you start an Erlang system that is going to talk to other
      Erlang systems, you must give it a name, for example:</p>
    <div class="example"><pre>
$ <span class="bold_code">erl -sname my_name</span></pre></div>
    <p>We will see more details of this later. If you want to
      experiment with distributed Erlang, but you only have one
      computer to work on, you can start two separate Erlang systems on
      the same computer but give them different names. Each Erlang
      system running on a computer is called an <strong>Erlang node</strong>.</p>
    <p>(Note: <span class="code">erl -sname</span> assumes that all nodes are in the same
      IP domain and we can use only the first component of the IP
      address, if we want to use nodes in different domains we use
      <span class="code">-name</span> instead, but then all IP address must be given in
      full.)</p>
    <p>Here is the ping pong example modified to run on two separate
      nodes:</p>
    <div class="example"><pre>
-module(tut17).

-export([start_ping/1, start_pong/0,  ping/2, pong/0]).

ping(0, Pong_Node) -&gt;
    {pong, Pong_Node} ! finished,
    io:format("ping finished~n", []);

ping(N, Pong_Node) -&gt;
    {pong, Pong_Node} ! {ping, self()},
    receive
        pong -&gt;
            io:format("Ping received pong~n", [])
    end,
    ping(N - 1, Pong_Node).

pong() -&gt;
    receive
        finished -&gt;
            io:format("Pong finished~n", []);
        {ping, Ping_PID} -&gt;
            io:format("Pong received ping~n", []),
            Ping_PID ! pong,
            pong()
    end.

start_pong() -&gt;
    register(pong, spawn(tut17, pong, [])).

start_ping(Pong_Node) -&gt;
    spawn(tut17, ping, [3, Pong_Node]).</pre></div>
    <p>Let us assume there are two computers called gollum and kosken.
      First a node is started on kosken, called ping, and then a node on gollum,
      called pong.</p>
    <p>On kosken (on a Linux/UNIX system):</p>
    <div class="example"><pre>
kosken&gt; <span class="bold_code">erl -sname ping</span>
Erlang (BEAM) emulator version 5.2.3.7 [hipe] [threads:0]

Eshell V5.2.3.7  (abort with ^G)
(ping@kosken)1&gt;</pre></div>
    <p>On gollum:</p>
    <div class="example"><pre>
gollum&gt; <span class="bold_code">erl -sname pong</span>
Erlang (BEAM) emulator version 5.2.3.7 [hipe] [threads:0]

Eshell V5.2.3.7  (abort with ^G)
(pong@gollum)1&gt;</pre></div>
    <p>Now the "pong" process on gollum is started:</p>
    <div class="example"><pre>
(pong@gollum)1&gt; <span class="bold_code">tut17:start_pong().</span>
true</pre></div>
    <p>And the "ping" process on kosken is started (from the code above you
      can see that a parameter of the <span class="code">start_ping</span> function is
      the node name of the Erlang system where "pong" is running):</p>
    <div class="example"><pre>
(ping@kosken)1&gt; <span class="bold_code">tut17:start_ping(pong@gollum).</span>
&lt;0.37.0&gt;
Ping received pong
Ping received pong 
Ping received pong
ping finished</pre></div>
    <p>As shown, the ping pong program has run. On the "pong" side:</p>
    <div class="example"><pre>
(pong@gollum)2&gt;
Pong received ping                 
Pong received ping                 
Pong received ping                 
Pong finished                      
(pong@gollum)2&gt;</pre></div>
    <p>Looking at the <span class="code">tut17</span> code, you see that the <span class="code">pong</span>
      function itself is unchanged, the following lines work in the same way
      irrespective of on which node the "ping" process is executes:</p>
    <div class="example"><pre>
{ping, Ping_PID} -&gt;
    io:format("Pong received ping~n", []),
    Ping_PID ! pong,</pre></div>
    <p>Thus, Erlang pids contain information about
      where the process executes. So if you know the pid of a process,
      the "!" operator can be used to send it a message disregarding
      if the process is on the same node or on a different node.</p>
    <p>A difference is how messages are sent to a registered process on
      another node:</p>
    <div class="example"><pre>
{pong, Pong_Node} ! {ping, self()},</pre></div>
    <p>A tuple <span class="code">{registered_name,node_name}</span> is used instead of
      just the <span class="code">registered_name</span>.</p>
    <p>In the previous example, "ping" and "pong" were started from
      the shells of two separate Erlang nodes. <span class="code">spawn</span> can also be
      used to start processes in other nodes.</p>
      <p>The next example is the ping pong program, yet again,
      but this time "ping" is started in another node:</p>
    <div class="example"><pre>
-module(tut18).

-export([start/1,  ping/2, pong/0]).

ping(0, Pong_Node) -&gt;
    {pong, Pong_Node} ! finished,
    io:format("ping finished~n", []);

ping(N, Pong_Node) -&gt;
    {pong, Pong_Node} ! {ping, self()},
    receive
        pong -&gt;
            io:format("Ping received pong~n", [])
    end,
    ping(N - 1, Pong_Node).

pong() -&gt;
    receive
        finished -&gt;
            io:format("Pong finished~n", []);
        {ping, Ping_PID} -&gt;
            io:format("Pong received ping~n", []),
            Ping_PID ! pong,
            pong()
    end.

start(Ping_Node) -&gt;
    register(pong, spawn(tut18, pong, [])),
    spawn(Ping_Node, tut18, ping, [3, node()]).</pre></div>
    <p>Assuming an Erlang system called ping (but not the "ping"
      process) has already been started on kosken, then on gollum this is done:</p>
    <div class="example"><pre>
(pong@gollum)1&gt; <span class="bold_code">tut18:start(ping@kosken).</span>
&lt;3934.39.0&gt;
Pong received ping
Ping received pong
Pong received ping
Ping received pong
Pong received ping
Ping received pong
Pong finished
ping finished</pre></div>
    <p>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.</p>
  

  <h3><a name="idp281692036">3.5 
        A Larger Example</a></h3>
    
    <p>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.</p>
    <p>Before starting, notice the following:</p>
    <ul>
      <li>
        <p>This example only shows the message passing logic - no
          attempt has been made to provide a nice graphical user
          interface, although this can also be done in Erlang.</p>
      </li>
      <li>
        <p>This sort of problem can be solved easier by use of
          the facilities in OTP, which also provide methods for
          updating code on the fly and so on (see
	  <span class="bold_code"><a href="javascript:erlhref('../../','doc/design_principles','des_princ.html#otp%20design%20principles');">
          OTP Design Principles</a></span>).</p>
      </li>
      <li>
        <p>The first program contains some inadequacies
          regarding handling of nodes which disappear.
          These are corrected in a later version of the program.</p>
      </li>
    </ul>
    <p>The messenger is set up by allowing "clients" to connect to
      a central server and say who and where they are. That is, a user
      does not need to know the name of the Erlang node where another user
      is located to send a message.</p>
    <p>File <span class="code">messenger.erl</span>:</p>
    <a name="ex"></a>
    <div class="example"><pre>
%%% Message passing utility.  
%%% User interface:
%%% logon(Name)
%%%     One user at a time can log in from each Erlang node in the
%%%     system messenger: and choose a suitable Name. If the Name
%%%     is already logged in at another node or if someone else is
%%%     already logged in at the same node, login will be rejected
%%%     with a suitable error message.
%%% logoff()
%%%     Logs off anybody at that node
%%% message(ToName, Message)
%%%     sends Message to ToName. Error messages if the user of this 
%%%     function is not logged on or if ToName is not logged on at
%%%     any node.
%%%
%%% One node in the network of Erlang nodes runs a server which maintains
%%% data about the logged on users. The server is registered as "messenger"
%%% Each node where there is a user logged on runs a client process registered
%%% as "mess_client" 
%%%
%%% Protocol between the client processes and the server
%%% ----------------------------------------------------
%%% 
%%% To server: {ClientPid, logon, UserName}
%%% Reply {messenger, stop, user_exists_at_other_node} stops the client
%%% Reply {messenger, logged_on} logon was successful
%%%
%%% To server: {ClientPid, logoff}
%%% Reply: {messenger, logged_off}
%%%
%%% To server: {ClientPid, logoff}
%%% Reply: no reply
%%%
%%% To server: {ClientPid, message_to, ToName, Message} send a message
%%% Reply: {messenger, stop, you_are_not_logged_on} stops the client
%%% Reply: {messenger, receiver_not_found} no user with this name logged on
%%% Reply: {messenger, sent} Message has been sent (but no guarantee)
%%%
%%% To client: {message_from, Name, Message},
%%%
%%% Protocol between the "commands" and the client
%%% ----------------------------------------------
%%%
%%% Started: messenger:client(Server_Node, Name)
%%% To client: logoff
%%% To client: {message_to, ToName, Message}
%%%
%%% Configuration: change the server_node() function to return the
%%% name of the node where the messenger server runs

-module(messenger).
-export([start_server/0, server/1, logon/1, logoff/0, message/2, client/2]).

%%% Change the function below to return the name of the node where the
%%% messenger server runs
server_node() -&gt;
    messenger@bill.

%%% This is the server process for the "messenger"
%%% the user list has the format [{ClientPid1, Name1},{ClientPid22, Name2},...]
server(User_List) -&gt;
    receive
        {From, logon, Name} -&gt;
            New_User_List = server_logon(From, Name, User_List),
            server(New_User_List);
        {From, logoff} -&gt;
            New_User_List = server_logoff(From, User_List),
            server(New_User_List);
        {From, message_to, To, Message} -&gt;
            server_transfer(From, To, Message, User_List),
            io:format("list is now: ~p~n", [User_List]),
            server(User_List)
    end.

%%% Start the server
start_server() -&gt;
    register(messenger, spawn(messenger, server, [[]])).


%%% Server adds a new user to the user list
server_logon(From, Name, User_List) -&gt;
    %% check if logged on anywhere else
    case lists:keymember(Name, 2, User_List) of
        true -&gt;
            From ! {messenger, stop, user_exists_at_other_node},  %reject logon
            User_List;
        false -&gt;
            From ! {messenger, logged_on},
            [{From, Name} | User_List]        %add user to the list
    end.

%%% Server deletes a user from the user list
server_logoff(From, User_List) -&gt;
    lists:keydelete(From, 1, User_List).


%%% Server transfers a message between user
server_transfer(From, To, Message, User_List) -&gt;
    %% check that the user is logged on and who he is
    case lists:keysearch(From, 1, User_List) of
        false -&gt;
            From ! {messenger, stop, you_are_not_logged_on};
        {value, {From, Name}} -&gt;
            server_transfer(From, Name, To, Message, User_List)
    end.
%%% If the user exists, send the message
server_transfer(From, Name, To, Message, User_List) -&gt;
    %% Find the receiver and send the message
    case lists:keysearch(To, 2, User_List) of
        false -&gt;
            From ! {messenger, receiver_not_found};
        {value, {ToPid, To}} -&gt;
            ToPid ! {message_from, Name, Message}, 
            From ! {messenger, sent} 
    end.


%%% User Commands
logon(Name) -&gt;
    case whereis(mess_client) of 
        undefined -&gt;
            register(mess_client, 
                     spawn(messenger, client, [server_node(), Name]));
        _ -&gt; already_logged_on
    end.

logoff() -&gt;
    mess_client ! logoff.

message(ToName, Message) -&gt;
    case whereis(mess_client) of % Test if the client is running
        undefined -&gt;
            not_logged_on;
        _ -&gt; mess_client ! {message_to, ToName, Message},
             ok
end.


%%% The client process which runs on each server node
client(Server_Node, Name) -&gt;
    {messenger, Server_Node} ! {self(), logon, Name},
    await_result(),
    client(Server_Node).

client(Server_Node) -&gt;
    receive
        logoff -&gt;
            {messenger, Server_Node} ! {self(), logoff},
            exit(normal);
        {message_to, ToName, Message} -&gt;
            {messenger, Server_Node} ! {self(), message_to, ToName, Message},
            await_result();
        {message_from, FromName, Message} -&gt;
            io:format("Message from ~p: ~p~n", [FromName, Message])
    end,
    client(Server_Node).

%%% wait for a response from the server
await_result() -&gt;
    receive
        {messenger, stop, Why} -&gt; % Stop the client 
            io:format("~p~n", [Why]),
            exit(normal);
        {messenger, What} -&gt;  % Normal response
            io:format("~p~n", [What])
    end.</pre></div>
    <p>To use this program, you need to:</p>
    <ul>
      <li>Configure the <span class="code">server_node()</span> function.</li>
      <li>Copy the compiled code (<span class="code">messenger.beam</span>) to
       the directory on each computer where you start Erlang.</li>
    </ul>
    <p>In the following example using this program,
      nodes are started on four different computers. If you do not have that
      many machines available on your network, you can start
      several nodes on the same machine.</p>
    <p>Four Erlang nodes are started up: messenger@super, c1@bilbo,
      c2@kosken, c3@gollum.</p>
    <p>First the server at messenger@super is started up:</p>
    <div class="example"><pre>
(messenger@super)1&gt; <span class="bold_code">messenger:start_server().</span>
true</pre></div>
    <p>Now Peter logs on at c1@bilbo:</p>
    <div class="example"><pre>
(c1@bilbo)1&gt; <span class="bold_code">messenger:logon(peter).</span>
true
logged_on</pre></div>
    <p>James logs on at c2@kosken:</p>
    <div class="example"><pre>
(c2@kosken)1&gt; <span class="bold_code">messenger:logon(james).</span>
true
logged_on</pre></div>
    <p>And Fred logs on at c3@gollum:</p>
    <div class="example"><pre>
(c3@gollum)1&gt; <span class="bold_code">messenger:logon(fred).</span>
true
logged_on</pre></div>
    <p>Now Peter sends Fred a message:</p>
    <div class="example"><pre>
(c1@bilbo)2&gt; <span class="bold_code">messenger:message(fred, "hello").</span>
ok
sent</pre></div>
    <p>Fred receives the message and sends a message to Peter and
      logs off:</p>
    <div class="example"><pre>
Message from peter: "hello"
(c3@gollum)2&gt; <span class="bold_code">messenger:message(peter, "go away, I'm busy").</span>
ok
sent
(c3@gollum)3&gt; <span class="bold_code">messenger:logoff().</span>
logoff</pre></div>
    <p>James now tries to send a message to Fred:</p>
    <div class="example"><pre>
(c2@kosken)2&gt; <span class="bold_code">messenger:message(fred, "peter doesn't like you").</span>
ok
receiver_not_found</pre></div>
    <p>But this fails as Fred has already logged off.</p>
    <p>First let us look at some of the new concepts that have
       been introduced.</p>
    <p>There are two versions of the <span class="code">server_transfer</span> function:
      one with four arguments (<span class="code">server_transfer/4</span>) and one with
      five (<span class="code">server_transfer/5</span>). These are regarded by Erlang as
      two separate functions.</p>
    <p>Notice how to write the <span class="code">server</span> function so that it calls
      itself, through <span class="code">server(User_List)</span>, and thus creates a loop.
      The Erlang compiler is "clever" and optimizes the code so that
      this really is a sort of loop and not a proper function call. But
      this only works if there is no code after the call. Otherwise,
      the compiler expects the call to return and make a proper
      function call. This would result in the process getting bigger
      and bigger for every loop.</p>
    <p>Functions in the <span class="code">lists</span> module are used. This is a very
      useful module and a study of the manual page is recommended
      (<span class="code">erl -man lists</span>).
      <span class="code">lists:keymember(Key,Position,Lists)</span> looks through a list
      of tuples and looks at <span class="code">Position</span> in each tuple to see if it
      is the same as <span class="code">Key</span>. The first element is position 1. If it
      finds a tuple where the element at <span class="code">Position</span> is the same as
      <span class="code">Key</span>, it returns <span class="code">true</span>, otherwise <span class="code">false</span>.</p>
    <div class="example"><pre>
3&gt; <span class="bold_code">lists:keymember(a, 2, [{x,y,z},{b,b,b},{b,a,c},{q,r,s}]).</span>
true
4&gt; <span class="bold_code">lists:keymember(p, 2, [{x,y,z},{b,b,b},{b,a,c},{q,r,s}]).</span>
false</pre></div>
    <p><span class="code">lists:keydelete</span> works in the same way but deletes
      the first tuple found (if any) and returns the remaining list:</p>
    <div class="example"><pre>
5&gt; <span class="bold_code">lists:keydelete(a, 2, [{x,y,z},{b,b,b},{b,a,c},{q,r,s}]).</span>
[{x,y,z},{b,b,b},{q,r,s}]</pre></div>
    <p><span class="code">lists:keysearch</span> is like <span class="code">lists:keymember</span>, but it
      returns <span class="code">{value,Tuple_Found}</span> or the atom <span class="code">false</span>.</p>
    <p>There are many very useful functions in the <span class="code">lists</span>
      module.</p>
    <p>An Erlang process (conceptually) runs until it does a
      <span class="code">receive</span> and there is no message which it wants to receive
      in the message queue. "conceptually" is used here because the Erlang
      system shares the CPU time between the active processes in
      the system.</p>
    <p>A process terminates when there is nothing more for it to do,
      that is, the last function it calls simply returns and does not call
      another function. Another way for a process to terminate is for
      it to call <span class="code">exit/1</span>. The argument to <span class="code">exit/1</span> has a
      special meaning, which is discussed later. In this example,
      <span class="code">exit(normal)</span> is done, which has the same effect as a
      process running out of functions to call.</p>
    <p>The BIF <span class="code">whereis(RegisteredName)</span> checks if a registered
      process of name <span class="code">RegisteredName</span> exists. If it exists, the pid of
      that process is returned. If it does not exist, the atom
      <span class="code">undefined</span> is returned.</p>
    <p>You should by now be able to understand most of the code in the
      messenger-module. Let us study one case in detail: a message is
      sent from one user to another.</p>
    <p>The first user "sends" the message in the example above by:</p>
    <div class="example"><pre>
messenger:message(fred, "hello")</pre></div>
    <p>After testing that the client process exists:</p>
    <div class="example"><pre>
whereis(mess_client) </pre></div>
    <p>And a message is sent to <span class="code">mess_client</span>:</p>
    <div class="example"><pre>
mess_client ! {message_to, fred, "hello"}</pre></div>
    <p>The client sends the message to the server by:</p>
    <div class="example"><pre>
{messenger, messenger@super} ! {self(), message_to, fred, "hello"},</pre></div>
    <p>And waits for a reply from the server.</p>
    <p>The server receives this message and calls:</p>
    <div class="example"><pre>
server_transfer(From, fred, "hello", User_List),</pre></div>
    <p>This checks that the pid <span class="code">From</span> is in the <span class="code">User_List</span>:</p>
    <div class="example"><pre>
lists:keysearch(From, 1, User_List) </pre></div>
    <p>If <span class="code">keysearch</span> returns the atom <span class="code">false</span>, some
      error has occurred and the server sends back the message:</p>
    <div class="example"><pre>
From ! {messenger, stop, you_are_not_logged_on}</pre></div>
    <p>This is received by the client, which in turn does
      <span class="code">exit(normal)</span> and terminates. If <span class="code">keysearch</span> returns
      <span class="code">{value,{From,Name}}</span> it is certain that the user is logged on and
      that his name (peter) is in variable <span class="code">Name</span>.</p>
      <p>Let us now call:</p>
    <div class="example"><pre>
server_transfer(From, peter, fred, "hello", User_List)</pre></div>
    <p>Notice that as this is <span class="code">server_transfer/5</span>, it is not the same
      as the previous function <span class="code">server_transfer/4</span>. Another
      <span class="code">keysearch</span> is done on <span class="code">User_List</span> to find the pid of
      the client corresponding to fred:</p>
    <div class="example"><pre>
lists:keysearch(fred, 2, User_List)</pre></div>
    <p>This time argument 2 is used, which is the second element in
      the tuple. If this returns the atom <span class="code">false</span>,
      fred is not logged on and the following message is sent:</p>
    <div class="example"><pre>
From ! {messenger, receiver_not_found};</pre></div>
    <p>This is received by the client.</p>
    <p> If <span class="code">keysearch</span> returns:</p>
    <div class="example"><pre>
{value, {ToPid, fred}}</pre></div>
    <p>The following message is sent to fred's client:</p>
    <div class="example"><pre>
ToPid ! {message_from, peter, "hello"}, </pre></div>
    <p>The following message is sent to peter's client:</p>
    <div class="example"><pre>
From ! {messenger, sent} </pre></div>
    <p>Fred's client receives the message and prints it:</p>
    <div class="example"><pre>
{message_from, peter, "hello"} -&gt;
    io:format("Message from ~p: ~p~n", [peter, "hello"])</pre></div>
    <p>Peter's client receives the message in
      the <span class="code">await_result</span> function.</p>
  
</div>
<div class="footer">
<hr>
<p>Copyright © 1996-2018 Ericsson AB. All Rights Reserved.</p>
</div>
</div>
</div></body>
</html>