Jump to content

Erlang Programming/Processes

From Wikibooks, open books for an open world

Erlang Processes and Messages

[edit | edit source]

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>" (where <N> is some integer).

Processes send messages to 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, see note 1).

This is a Process Message Diagram for the execution of: chain_hello:start(1).

start(1)
   |
spawns -----------> listen(1)
   |                   |
   |                spawns --------------------> listen(0)
   |                   |                            |
   |                sends ----> speak ----------> prints --> "hello world 0"
   |                   |                            |
 sends --> speak --> prints --> "hello world 1"     |
                       |                            |
                       ok                           ok

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 ---- %
%
% 14> chain_hello:start(4).
% done
% hello world!4
% hello world!3
% hello world!2
% okhello world!1
% hello world!0