Erlang (programming language)/Tutorials/Processes

From Citizendium
Jump to navigation Jump to search

Erlang Processes and Messages

Processes are easy to create and control in erlang. The program chain_hello.erl builds a chain of processes as long as you like. Each process creates one process then sends a message to it. The program creates a chain of N processes which each print out hello world! N. Processes send messages and receive messages from one another. Messages are read with pattern matching. The messages are matched in a fifo(first in, first out) way.

Note 1: The order of the final output depends on process scheduling.

Note 2: Time flows downward(in each vertical line for each process, see note 1).


This is a minimal UML sequence diagram showing the processes and messages for the execution of:

chain_hello:start(1). 
UML sequence notation: Processes start in boxes. Dotted lines are life lines. Processes time lines end in X's.  
Note: Some of the details of have been left out for tutorial purposes. 
      The diagram has English mixed with code.
Local notation: Command line output is in quotes. Messages are in curly braces. 
+——————————+                  
| start(1) | 
+——————————+
   ¦              +———————————+
spawns  ———————>  | listen(1) |
   ¦              +———————————+
   ¦                    ¦                      +———————————+
   ¦                  spawns ————————————————> | listen(0) |
   ¦                    ¦                      +———————————+
   ¦                    ¦                          ¦
sends  —> {speak} —> prints  —> "hello world 1"    ¦
   ¦                    ¦                          ¦
   ¦                  sends ——> {speak} ———————> prints  ———> "hello world 0"
   ¦                    ¦                          ¦
   X                    X                          X

Program listing for: chain_hello.erl

-module(chain_hello). 
-compile(export_all).
                                                            %
start(N)->                                                  % startup
       Pid1 = spawn(chain_hello, listen, [N]),
       Pid1 ! speak,
       io:format("done \n").
                                                            %
listen(0)->                                                 % base case
       receive
                speak ->
                       io:format("hello world!~w\n", [0])
       end;
listen(N)->                                                 % recursive case
       Pid2= spawn(chain_hello, listen, [N-1]),
       Pid2! speak,
       receive
               speak->
                       io:format("hello world!~w\n", [N])
       end.
% ---- sample output for chain_hello:start(1) --- %
%
% 14> chain_hello:start(1).
% done
% okhello world!1
% hello world!0
%
% ---- sample output for chain_hello:start(4) --- %
%
% 14> chain_hello:start(4).
% done
% hello world!4
% hello world!3
% hello world!2
% okhello world!1
% hello world!0