Erlang (programming language)/Tutorials/Processes

From Citizendium
< Erlang (programming language)‎ | Tutorials
Revision as of 19:18, 19 April 2008 by imported>Eric Evers (New page: ==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...)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
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, 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