Crash Course
Crash Course
E r i c sso n S o f t wa r e T e c h n o l o g y AB ,
Al l r i g h t s R e se r v e d 1
Ericsson Software Technology AB, Erlang Systems; All rights reserved Erlang Crash Course 1
Erlang Crash Course
Erlang Crash Course
Erlang Systems
http://www.ericsson.se/erlang
Ericsson Software Technology AB
This is a quick crash course on Erlang. You will get the general picture of
how to use the language. However this is not a detailed coverage of the
language and its use.
Erlang Crash Course
E r i c sso n S o f t wa r e T e c h n o l o g y AB ,
Al l r i g h t s R e se r v e d 2
Ericsson Software Technology AB, Erlang Systems; All rights reserved Erlang Crash Course 2
2 Introduction
2 Sequential Erlang
2 Concurrent Erlang
2 Fault Tolerance
2 Interoperability
2 Distribution
2 Examples & Exercises
Contents
Contents
During this crash course we cover these topics. We will leave out some
details, but most of it is here.
Erlang Crash Course
E r i c sso n S o f t wa r e T e c h n o l o g y AB ,
Al l r i g h t s R e se r v e d 3
Ericsson Software Technology AB, Erlang Systems; All rights reserved Erlang Crash Course 3
Introduction
Introduction
2 History of Erlang
2 Overview of Erlang
2 How To Run
This session contains some initial background information.
Erlang Crash Course
E r i c sso n S o f t wa r e T e c h n o l o g y AB ,
Al l r i g h t s R e se r v e d 4
Ericsson Software Technology AB, Erlang Systems; All rights reserved Erlang Crash Course 4
History of Erlang
History of Erlang
1987 First experiments
1988-89 User prototyping telecom applications
1990 Presented at ISS90
1991 A new fast implementation
1992 Product projects started
1993 Distribution is added
1994 Products launched
1997 Erlang general availability
1995- Several projects started
Erlang came out of the Computer Science Lab at Ellemtel Utvecklings AB,
headed by Bjarne Dcker, as the result of a project trying to find
programming languages suitable for telecom applications.
The lab tried various languages available at that time, and found the need for
a language that could handle massive concurrency and having good support
for fault tolerance. Since no language could meet these constraints, a decision
were taken to construct a new language borrowing ideas that were good.
After some initial work, a prototype project within Ericsson were located, and
some real user response could be obtained.
The outcome of these experiments were very promising and development
continued.
Today we are in a situation were we have a lot of experience from telecom
applications, and Erlang certainly fills its place here.
1993 Erlang Systems were founded in order to handle consultancy services,
training, support and marketing.
Erlang Crash Course
E r i c sso n S o f t wa r e T e c h n o l o g y AB ,
Al l r i g h t s R e se r v e d 5
Ericsson Software Technology AB, Erlang Systems; All rights reserved Erlang Crash Course 5
Overview of Erlang
Overview of Erlang
HW/OS
ERTS (Erlang RunTime System)
Support Libraries
Applications
The Erlang system is based on a runtime environment which is the basis for
program execution. This makes Erlang programs easily portable since only
the ERTS needs to be ported. ERTS is currently ported to a number of
platforms.
Applications are typically written using direct calls into the runtime system or
using support libraries for special functionality, e.g. I/O.
Together with the runtime system and the support libraries the distribution
contains applications, such as compilers and debuggers.
To really levitate your application building you should spend some time
going through the documentation covering the support libraries.
Erlang Crash Course
E r i c sso n S o f t wa r e T e c h n o l o g y AB ,
Al l r i g h t s R e se r v e d 6
Ericsson Software Technology AB, Erlang Systems; All rights reserved Erlang Crash Course 6
How To Run
How To Run
Erlang development consists of editing/
compiling/ running.
2 Edit in your favourite editor.
2 Start an Erlang shell ( erl )
2 Compile (c(filename).)
2 Run your example.
Erlang source code files should have the suffix . e r l
Besides running your code from the shell you can try out various stuff, please
do that while going through the crash course.
Erlang Crash Course
E r i c sso n S o f t wa r e T e c h n o l o g y AB ,
Al l r i g h t s R e se r v e d 7
Ericsson Software Technology AB, Erlang Systems; All rights reserved Erlang Crash Course 7
Sequential Erlang
Sequential Erlang
2 Data types
2 Pattern matching
2 Functions
2 Control structures
2 BIFs
2 Special items
Erlang is a very small language but contains a number of powerful
mechanisms that nevertheless gives you what you want in terms of
expressability. In this session we will cover the sequential part of Erlang.
Erlang Crash Course
E r i c sso n S o f t wa r e T e c h n o l o g y AB ,
Al l r i g h t s R e se r v e d 8
Ericsson Software Technology AB, Erlang Systems; All rights reserved Erlang Crash Course 8
Data types - Terms
Data types - Terms
The usual ones ....
2 Integers (e.g. -4711, 17, 42, 4711)
2 Characters (are really special integers)
(e.g. $A meaning 65)
2 Floats (e.g. -42.0, 17,4711)
2 Bignums (e.g. 471117471142424242424241...)
These are the usual data types.
Bignums are a special form of integers allowing (almost) indefinite integers.
Integers overflow into bignums.
The notion t e r m is used as a generic name for any data in Erlang.
Erlang Crash Course
E r i c sso n S o f t wa r e T e c h n o l o g y AB ,
Al l r i g h t s R e se r v e d 9
Ericsson Software Technology AB, Erlang Systems; All rights reserved Erlang Crash Course 9
More Simple Types
More Simple Types
2 Atoms (e.g. t h i si sa n a t o m ,
o r _ l i k e _ t h i s)
2 Variables (e.g. No t a n a t o m ,
Or L i k e T h i s)
2 References
2 Pids
2 Ports
An atom could be compared to a constant. The value of the atom is the atom
itself. An atom name starts with a lower case letter.
A variable is a variable in the mathematical sense. You cannot change the
value of a variable once it has been bound. A variable name starts with an
upper case letter.
A reference is nothing but a unique value within the system. This value is not
unique among several invocations of the runtime system.
The other types process identifier (Pids) and ports we will get back to later
on.
Erlang Crash Course
E r i c sso n S o f t wa r e T e c h n o l o g y AB ,
Al l r i g h t s R e se r v e d 1 0
Ericsson Software Technology AB, Erlang Systems; All rights reserved Erlang Crash Course 10
Structured Types
Structured Types
2 Tuples (e.g. {}, {1,a}, {{a,b}, 1})
2 Lists (e.g. [], [1,2], [1,a,{1}, [1,2]])
2 Strings are special lists of ASCII values,
(e.g. This is a string)
2 Binaries
A tuple is a container of a fixed number of terms. This is the equivalent of a
vector (taking all sorts of scalars) in other languages.
A list is a container of a variable number of terms. This is the equivalent of a
linked list.
A binary is really a blob of memory. It is used as an platform independent
storage format. Terms may be transformed into binaries, and vice versa.
Erlang Crash Course
E r i c sso n S o f t wa r e T e c h n o l o g y AB ,
Al l r i g h t s R e se r v e d 1 1
Ericsson Software Technology AB, Erlang Systems; All rights reserved Erlang Crash Course 11
Constructing Data
Constructing Data
2 Data is declared and constructed by simply
typing terms down.
2 For lists there is a special construction, to
prepend an element to a list L :
[ e l e m e n t | L ]
this should be read as the list starting with
e l e m e n t and followed by the list L .
Erlang is a dynamically typed language. You cannot declare a type, the
system keeps track of this for you.
The list construction may also be used to extract element from a list, suppose
we have the expression:
[ A | L ] = [ 1 , 2 , 3 ]
then A will be bound to 1, whereas L will be bound to [ 2 , 3 ]
Erlang Crash Course
E r i c sso n S o f t wa r e T e c h n o l o g y AB ,
Al l r i g h t s R e se r v e d 1 2
Ericsson Software Technology AB, Erlang Systems; All rights reserved Erlang Crash Course 12
Pattern Matching
Pattern Matching
2 Assignment
A = 2
2 Test
A = 2,..... A = B
2 Extracting information
{FirstElem, SecondElem} = Tuple
Pattern matching is of fundamental importance in Erlang. Everything is based
on it.
A pattern is as the name suggests a pattern of Erlang terms. Matching is based
on the following:
What values should I assign to variables in the left hand side of a pattern
matching to make the = statement a true statement.
In our first example, assuming that A has no value, we see that in order for
the statement A = 2 to be true A must be 2.
In the second example, when we use matching for testing purposes we have
assigned A the value 2, and then later we use it to check whether A = B is
true, i.e. we check whether 2 = B is true. This is so if B holds the value 2.
In the last example pattern matching is used to extract elements from a tuple.
Thus if T u p l e contained the value { f i r st , se c o n d } then
F i r st E l e m would be bound to f i r st , and Se c o n d E l e m
to se c o n d .
If a matching fails, it causes a runtime failure.
Erlang Crash Course
E r i c sso n S o f t wa r e T e c h n o l o g y AB ,
Al l r i g h t s R e se r v e d 1 3
Ericsson Software Technology AB, Erlang Systems; All rights reserved Erlang Crash Course 13
Functions
Functions
double(X) ->
2 * X.
isemptylist([]) ->
true;
isemptylist(_Other) ->
false.
Functions consist of two parts, the h e a d and the b o d y , these are
separated by the ->. The head consists of the name of the function
(d o u b l e resp. i se m p t y l i st above) plus a argument sequence
within parenthesis.
Arguments are given a value at a call to a function. The last expression
evaluated in the body of a function is the return value of the function.
A function may consist of several clauses (e.g. i se m p t y l i st above).
Clauses are separated by ;. A function definition is ended using ..
In this example we have defined two functions, d o u b l e / 1 taking a
number as argument and returns two times this number.
The function i se m p t y l i st / 1 uses pattern matching to check
whether the argument is the empty list ([]) or not. The returned values are
ordinary atoms, not Boolean values.
Erlang functions are always call by value. No variables may be imported to or
exported out of a function.
Erlang Crash Course
E r i c sso n S o f t wa r e T e c h n o l o g y AB ,
Al l r i g h t s R e se r v e d 1 4
Ericsson Software Technology AB, Erlang Systems; All rights reserved Erlang Crash Course 14
Functions - Modules
Functions - Modules
A module:
-module(mymod).
-export([double/1]).
double(X) ->
2*X.
quadruple(X) ->
double(double(X)).
Erlang functions must be placed in modules. There are both source modules
and binary modules. The binary ones are compiled versions of the source
module.
A source module has the suffix .erl, e.g. mymod.erl above. The compiled
version has the suffix .jam.
The structure of a source module is as above, first we need to declare the
name of the module as well as the functions that we export. Naming of
functions are based on the schema n a m e / a r i t y , which uniquely
designates a function.
Exported functions are accessible from other modules. All functions within a
module is callable from the module itself without exporting them.
Erlang Crash Course
E r i c sso n S o f t wa r e T e c h n o l o g y AB ,
Al l r i g h t s R e se r v e d 1 5
Ericsson Software Technology AB, Erlang Systems; All rights reserved Erlang Crash Course 15
Guards
Guards
%%% Checks if the argument is an atom or an integer
atomorint(Atom) when atom(Atom) ->
true;
atomorint(Int) when integer(Int) ->
true;
atomorint(_Other) ->
false.
The reserved word wh e n may be used in the head of a clause to add
special constraints, so called guards to a clause. Guards are evaluated during
the selection of a clause. Due to this, the selection of guards are limited.
Multiple guards may be given as a comma separated sequence after the when.
The comma is interpreted as an and.
Examples of guards are:
== (equality)
=/= (non equality)
lists(L) (checks if L is a list)
tuple(Tup)
binary(Bin)
pid(Pid)
port(Port)
length(List)
relational operators
Erlang Crash Course
E r i c sso n S o f t wa r e T e c h n o l o g y AB ,
Al l r i g h t s R e se r v e d 1 6
Ericsson Software Technology AB, Erlang Systems; All rights reserved Erlang Crash Course 16
Control Structures
Control Structures
%%% The case statement
foo() ->
case bar(X) of
{case1, Arg} ->
handle_it(Arg);
{case2, Value} ->
handle2(Value);
Anything ->
true
end,....
%%% If statement
zot(X) ->
if
X == 2 ->
xeq2();
X == 3 ->
xeq3();
true ->
true
end,....
The case statement allows the user to base continued execution on an
evaluated value. The case statement contains one or several clauses. The first
(top-down) matching clause is chosen for execution.
At least one clause must match.
The if statement may only use guard operators in the tests.
Erlang Crash Course
E r i c sso n S o f t wa r e T e c h n o l o g y AB ,
Al l r i g h t s R e se r v e d 1 7
Ericsson Software Technology AB, Erlang Systems; All rights reserved Erlang Crash Course 17
BIFs
BIFs
2 OS related functions, date(), time()
2 Process related functions
2 Math
2 ... and more
When writing Erlang applications the code is drawn from essentially three
sources.
1) Your own code
2) Library functions supplied with Erlang systems, e.g. socket
3) Built In Functions (BIFs).
The BIFs are functions that are impossible to do in Erlang or otherwise
would be very inefficient.
Erlang Crash Course
E r i c sso n S o f t wa r e T e c h n o l o g y AB ,
Al l r i g h t s R e se r v e d 1 8
Ericsson Software Technology AB, Erlang Systems; All rights reserved Erlang Crash Course 18
Special Items
Special Items
%%% To call any function in runtime
callany(Module, Function, Args) ->
apply(Module, Function, Args).
The BIF apply/3 allows runtime creation of a call. The function returns
whatever the called function returns or failure.
This is a very powerful instrument.
Erlang Crash Course
E r i c sso n S o f t wa r e T e c h n o l o g y AB ,
Al l r i g h t s R e se r v e d 1 9
Ericsson Software Technology AB, Erlang Systems; All rights reserved Erlang Crash Course 19
Concurrent Erlang
Concurrent Erlang
2 Creating processes
2 Process communication
2 Timeouts
2 Registration
During this session we will talk about how to create process, how they
communicate with each other.
You must keep in mind that Erlang processes are extremely light-weight. Do
not be afraid of using a lot of processes.
Erlang Crash Course
E r i c sso n S o f t wa r e T e c h n o l o g y AB ,
Al l r i g h t s R e se r v e d 2 0
Ericsson Software Technology AB, Erlang Systems; All rights reserved Erlang Crash Course 20
Creating Processes
Creating Processes
Before
After
PidB = spawn(mymod, myfunc, [arg1])
A
B
A
To create a new process we use the BIF sp a wn / 3 . The BIF takes three
arguments, the name of a module and function that the new process will start
to execute after creation, and an parameter specifying the arguments to this
function, this must be a list where the elements corresponds to the required
arguments of the called function.
The BIF returns the process identifier (Pid) of the newly created process. The
new process knows nothing about the creator (c.f. fork).
Functions used in the spawn call must be exported.
Erlang Crash Course
E r i c sso n S o f t wa r e T e c h n o l o g y AB ,
Al l r i g h t s R e se r v e d 2 1
Ericsson Software Technology AB, Erlang Systems; All rights reserved Erlang Crash Course 21
Process Communication
Process Communication
A B
B ! {mymsg, [1,2,3]}
....
receive
{mymsg, List} ->
handle(List);
AnyMsg ->
true
end,
To send a message to another process we need to know its pid. Any term may
be sent as a message. In the example above process A sends a tuple to process
B. The message is tagged with the atom m y m sg , to allow selection at
the receiver end.
Messages are asynchronous, thus A continues to execute after sending the
message. A will not be notified if B is non-existent (we get back to this later
on).
To be able to receive a message a process must execute a receive statement.
A receive statement may contain several clauses, and the selection of a clause
is based on pattern matching.
Each process is said to have a mailbox, where messages are stored in a queue.
As soon as a process executes a receive statement, the first message in the
box is matched top-down against the clauses, if any of them matches, the
message is removed from the mailbox and execution proceeds. If the message
doesnt match any clause, the message is left in the mailbox and the next
message is tried in a similar fashion. If no message matches, then the process
is put to sleep until such a message appears.
Erlang Crash Course
E r i c sso n S o f t wa r e T e c h n o l o g y AB ,
Al l r i g h t s R e se r v e d 2 2
Ericsson Software Technology AB, Erlang Systems; All rights reserved Erlang Crash Course 22
Time-outs
Time-outs
receive
SomeMsg ->
handle_it(SomeMsg)
after 1000 ->
handle_timeout()
end,
...
%%% To specify a maximum waiting time
To avoid locking processes, a time out may be specified in the receive
statement. The time is specified in milliseconds. If no matching message is
received within the given time frame, the time-out clause is chosen.
Erlang Crash Course
E r i c sso n S o f t wa r e T e c h n o l o g y AB ,
Al l r i g h t s R e se r v e d 2 3
Ericsson Software Technology AB, Erlang Systems; All rights reserved Erlang Crash Course 23
Example Usage
Example Usage
%%% Sleep Time ms
sleep(Time) ->
receive
after Time ->
true
end.
%%% Flush messages
flush() ->
receive
Any ->
flush()
after 0 ->
true
end,
....
Using a 0 (zero) as time-out time means simply that if no message is
applicable we should time-out, or as in the example above leave the receive
statement.
The second example shows how the message queue may be flushed.
Erlang Crash Course
E r i c sso n S o f t wa r e T e c h n o l o g y AB ,
Al l r i g h t s R e se r v e d 2 4
Ericsson Software Technology AB, Erlang Systems; All rights reserved Erlang Crash Course 24
Registration
Registration
A
register(myname, self()),
B
myname ! Msg
A process may be registered under a name, an alias. To do this the BIF
r e g i st e r / 2 must be used. The function takes two arguments, the
name of the process and the process id. Above we have used the BIF
se l f / 0 to obtain our own process id.
Other processes may now use the name when communicating with the named
process. In this way we do not have to circulate the pid around the system.
The name of the process must be unique within the Erlang system. If the
process dies the name is no longer valid.
Erlang Crash Course
E r i c sso n S o f t wa r e T e c h n o l o g y AB ,
Al l r i g h t s R e se r v e d 2 5
Ericsson Software Technology AB, Erlang Systems; All rights reserved Erlang Crash Course 25
Fault Tolerance
Fault Tolerance
2 Exits
2 Exit signals
2 Trapping exits
Fault tolerance is one of the fundamental issues in Erlang. The basic
mechanism for this is process links and exit signalling.
Erlang Crash Course
E r i c sso n S o f t wa r e T e c h n o l o g y AB ,
Al l r i g h t s R e se r v e d 2 6
Ericsson Software Technology AB, Erlang Systems; All rights reserved Erlang Crash Course 26
2 Exiting a spawn function
2 Exiting
Exits
Exits
start() ->
do_things(),
true.
exit(Reason)
There are three ways for a process to terminate:
A process could terminate due to falling over the function edge (of a spawn
function), i.e. have nothing more to execute.
A process may also encounter an error, such as division by zero. This also
terminates the process.
A process may also choose to terminate using the BIF e x i t / 1 .
There is always a reason associated with exiting. In the first case the reason is
called n o r m a l . In the second case, the nature of the failure is the reason,
e.g. function clause missing. Finally in the last case the reason is supplied in
the call to e x i t / 1 .
Erlang Crash Course
E r i c sso n S o f t wa r e T e c h n o l o g y AB ,
Al l r i g h t s R e se r v e d 2 7
Ericsson Software Technology AB, Erlang Systems; All rights reserved Erlang Crash Course 27
Exit Signals
Exit Signals
link(A)
A
B
link
A
B
A
X = 1/0
By using the BIF l i n k / 1 bi-directional links may be set up between
processes. A process may link to multiple processes. When a process dies
with reason different from n o r m a l , an exit signal is sent along the
links, killing the other processes in the linked set. Exit signal propagates
through linked sets.
Erlang Crash Course
E r i c sso n S o f t wa r e T e c h n o l o g y AB ,
Al l r i g h t s R e se r v e d 2 8
Ericsson Software Technology AB, Erlang Systems; All rights reserved Erlang Crash Course 28
Trapping Exits
Trapping Exits
A
process_flag(trap_exit, true)
B
A B
receive
{EXIT, B, Reason} ->
.....
A process may choose to trap exits. This means that exit signals from the
linked set will be transformed into exit messages that may be received by the
exit trapping process. Exit signals will not propagate through the exit trapping
process.
The purpose of this arrangement is to let the process A know about the failure
of B and thus take action.
An exit trapping process may choose to exit as well, but this must be done
explicitly.
Erlang Crash Course
E r i c sso n S o f t wa r e T e c h n o l o g y AB ,
Al l r i g h t s R e se r v e d 2 9
Ericsson Software Technology AB, Erlang Systems; All rights reserved Erlang Crash Course 29
Interoperability
Interoperability
Erlang program
Other program
connected
process
port
pipe
Erlang interoperates with other programs through ports. A port is a bi-
directional communication path, typically using pipes.
A port is opened by a process, this process is known as the connected
process. This process is allowed to send messages to the port and it is also
the designated receiver of messages from the port. These messages originate
from the other program connected to the port.
In an application the connected process typically acts as a concentrator and
distributor of the information flow between processes and the other program.
The other program is supposed to read and write to stdin/stdout (typically).
Erlang Crash Course
E r i c sso n S o f t wa r e T e c h n o l o g y AB ,
Al l r i g h t s R e se r v e d 3 0
Ericsson Software Technology AB, Erlang Systems; All rights reserved Erlang Crash Course 30
Using Ports
Using Ports
Port ! {self(), {command, [1,2,3,4,5]}}
A
Port = open_port({spawn, myprog}, [{packet, 2}])
myprog
[0,5,1,2,3,4,5]
len = read(0,buff,2);
len = buff[0]<<8 | buff[1];
read(0, buff, len);
A process needs to open a port before using it. In this case we specify that the
port should be connected to a spawned OS program called m y p r o g . We
also say that we use packages with a 2 byte length header prepended to the
message. The message sent is a list of 8 bit integers while the received
message is a sequence of bytes (C-side).
Note that the receiving program should check the read length.
Handling of lengths etc., is not needed in the Erlang environment. At the
Erlang side only lists are seen.
As an option (which is more common), binaries may be used at the Erlang
side. Other package sizes are supported as well.
There are C-libraries helping out with encoding/decoding Erlang terms.
Erlang Crash Course
E r i c sso n S o f t wa r e T e c h n o l o g y AB ,
Al l r i g h t s R e se r v e d 3 1
Ericsson Software Technology AB, Erlang Systems; All rights reserved Erlang Crash Course 31
Distribution
Distribution
[email protected] [email protected]
[email protected]
> erl -name node1 > erl -name node2 > erl -name node1
B
C
B ! Msg
link(C)
%% Monitoring
monitor_node(Node, true),
receive
{nodedown, Node} ->
down
end
The Erlang distribution is based on nodes. A node is an Erlang system started
in distributed mode and given a name, e.g. erl -name thename.
A node name consists of a given name and the host name. Thus above the
given names are n o d e 1 , n o d e 2 and n o d e 1 (again). The
uniqueness of nodenames are given by the network host names.
Message sending and process linkage is transparent to the application.
Processes do not have to reside within the same node.
Erlang Crash Course
E r i c sso n S o f t wa r e T e c h n o l o g y AB ,
Al l r i g h t s R e se r v e d 3 2
Ericsson Software Technology AB, Erlang Systems; All rights reserved Erlang Crash Course 32
Distribution (more)
Distribution (more)
2 To spawn:
spawn(Node, Mod, Func, Args)
2 Using registered names:
{thename, Node} ! Msg
When using registered names on other nodes, no notification of missing name
is made.
Erlang Crash Course
E r i c sso n S o f t wa r e T e c h n o l o g y AB ,
Al l r i g h t s R e se r v e d 3 3
Ericsson Software Technology AB, Erlang Systems; All rights reserved Erlang Crash Course 33
Examples/Exercises
Examples/Exercises
2 Simple recursion
2 Simple process communication
2 Simple RPC
In this session we will give you three simple examples of code.
Erlang Crash Course
E r i c sso n S o f t wa r e T e c h n o l o g y AB ,
Al l r i g h t s R e se r v e d 3 4
Ericsson Software Technology AB, Erlang Systems; All rights reserved Erlang Crash Course 34
Simple Recursion
Simple Recursion
%% Finds out if Item is in the List
member(Item, [Item | _Rest]) ->
true;
member(Item, [_NotItem | Rest]) ->
member(Item, Rest);
member(_Item, []) ->
false.
In the first clause we rely on pattern matching between the searched item and
the head of the list.
If this is not the case (clause 2) we try if there are at least one element in the
list, and if so we simply make a recursive call to try the remainder of the list.
Finally in the last clause we have reached the empty list without finding the
wanted item, and thus we return false.
Note that we have implicitly tested for a list as the second element
everywhere. If this function is called with something else as second argument
the call fails.
NB! Erlang employs Last Call Optimization (LCO) which is a technique that
reuses stack space, thus you do no have to worry about using too much stack
here.
Erlang Crash Course
E r i c sso n S o f t wa r e T e c h n o l o g y AB ,
Al l r i g h t s R e se r v e d 3 5
Ericsson Software Technology AB, Erlang Systems; All rights reserved Erlang Crash Course 35
Simple Process Communication..
Simple Process Communication..
%%% Sends a message back and forth
-module(echo).
-export([second/1]).
start() ->
Pid = spawn(echo, second, []),
Pid ! {hello, self()},
receive
_What ->
true
end.
In this example a process creates an echo process (see next slide), then it
sends a message to the echo process and then wait for the reply. After this the
process terminates.
Erlang Crash Course
E r i c sso n S o f t wa r e T e c h n o l o g y AB ,
Al l r i g h t s R e se r v e d 3 6
Ericsson Software Technology AB, Erlang Systems; All rights reserved Erlang Crash Course 36
..Simple Process Communication
..Simple Process Communication
%% And the second process
second() ->
receive
{Msg, Pid} when pid(Pid) ->
Pid ! Msg;
Else ->
true
end,
second().
This is the code for the echo process. The process sits in a loop waiting for a
message to appear. The process reacts to messages being tuples containing a
message and a process id. The message is returned to the pid.
All other messages are discarded.
Note that this process never terminates.
Erlang Crash Course
E r i c sso n S o f t wa r e T e c h n o l o g y AB ,
Al l r i g h t s R e se r v e d 3 7
Ericsson Software Technology AB, Erlang Systems; All rights reserved Erlang Crash Course 37
Simple RPC (server)
Simple RPC (server)
%%% Assume the server is registered under the name r e x
loop() ->
receive
{From, {apply, M, F, A}} ->
From ! {rex, node(), apply(M, F, A)}
loop();
_Other ->
loop()
end.
This is the essential loop needed for an RPC server.
The server receives requests from clients, uses apply to evaluate the requests
and then returns the answer to the originator.
This is a simplified solution where no error handling is done.
The BIF n o d e / 0 returns the node name.
Erlang Crash Course
E r i c sso n S o f t wa r e T e c h n o l o g y AB ,
Al l r i g h t s R e se r v e d 3 8
Ericsson Software Technology AB, Erlang Systems; All rights reserved Erlang Crash Course 38
Simple RPC (client)
Simple RPC (client)
%% This is all the client needs to do
call(Node, M, F, A) ->
{rex, Node} ! {self(), {apply, M, F, A}},
receive
{rex, Node, What} ->
What
end.
This is the code needed for basic client RPC calls.
The client sends a message to a registered process at the given node and then
waits for the reply.
This solution might be extended to handle e.g. malfunctioning servers.
Erlang Crash Course
E r i c sso n S o f t wa r e T e c h n o l o g y AB ,
Al l r i g h t s R e se r v e d 3 9
Ericsson Software Technology AB, Erlang Systems; All rights reserved Erlang Crash Course 39
Exercises
Exercises
2 Write a function append(List1, List2) that
returns the concatenation of the lists.
2 Write a program having two processes sending
a message back and forth M times, and then
terminates.
2 Modify the program to run on two nodes.
It is up to you to solve these....
Erlang Crash Course
E r i c sso n S o f t wa r e T e c h n o l o g y AB ,
Al l r i g h t s R e se r v e d 4 0
Ericsson Software Technology AB, Erlang Systems; All rights reserved Erlang Crash Course 40
Sources of Information
Sources of Information
2 http://www.ericsson.se/erlang
2 Concurrent Programming in ERLANG;
Armstrong, Virding, Wikstrm, Williams;
Prentice Hall, ISBN 0-13-508301-X
2 Courses @ Erlang Systems
The book covers the general ideas as well as some examples. The web site
gives you additional information as well as more up-to-date information
about releases etc.
In the distribution you will find on-line manuals that gives you the details not
found in the book.
Erlang Systems is offering an extensive set of courses covering Erlang. For
further information see the web site.