SlideShare a Scribd company logo
Distributed Features of Erlang
2
Concurrency
● A deep understanding of concurrency is “hardwired” into our brains
● The world is parallel
● Erlang programs model how we think and interact:
– No shared memory
● People function as independent entities who communicate by sending
messages:
– Erlang is based on pure message passing
– No locking needed
● If somebody dies, other people will notice:
– Processes can be linked together
3
Erlang Processes
● Erlang processes belong to the programming language, not to the OS
– Creating and destroying processes is very fast
– Sending messages between processes is very fast
– Processes behave the same way on all operating systems
– A very large number of processes is feasible
– Processes share no memory and are completely independent
– Creating a process takes 4–5ms
– The only way for processes to interact is through message passing
4
Concurrency Primitives
● Pid = spawn(Fun)
– Create a new concurrent process that evaluates Fun. The primitive
returns the process identifier
● Pid ! Message
– Send Message to the process Pid. The send is nonblocking
(asynchronous). The value of the expression is the message itself.
Therefore, Pid1 ! Pid2 ! ... ! PidN ! M sends M to all mentioned
processes
● receive ... end
– Receive a message according to a pattern.
5
A Simple Example
%% area_server.erl
-module(area_server).
-export([loop/0]).
loop()->
receive
{rectangle, Width, Ht} -> io:format(“A=~p~n”,[Width*Ht]), loop();
{circle, R} -> io:format(“A=~p~n”,[3.14159*R*R]), loop();
Other -> io:format(“Error: ~p~n”, [Other]), loop()
end.
%% Usage:
1> Pid = spawn(fun area_server:loop/0).
<0.36.0>
2> Pid ! {rectangle, 6, 10}.
A=60
{rectangle, 6, 10}
6
Client-server
● Actually, “request-response”
● To receive a response, a request must contain the pid of the requester
● Received responses must be matched with pending requests with the
help of pid's and, if necessary, sequence numbers
● Requests can be disguised as (remote) procedure calls
7
Client-server example
%% area_server_final.erl
-module(area_server_final).
-export([start/0,area/2]).
start() -> spawn(fun loop/0).
area(Pid, What) -> rpc(Pid, What).
rpc(Pid, Request) ->
Pid ! {self(), Request},
receive
{Pid, Response} -> Response
End.
loop() ->
receive
{From, {rectangle, W, H}} -> From ! {self(), W*H}, loop();
%%....
end.
8
Client-server example (cont.)
%% At shell prompt
1> Pid = area_server_final:start().
<0.36.0>
2> area_server_final:area(Pid, {rectangle, 10, 8}).
80
9
Receive with timeout and guards
● receive...end can have and optional after clause that takes Time in
milliseconds and returns an expression if no message is received after
Time. Time can be infinity.
● The receive clause itself can be empty. Good for timers:
sleep(T) -> receive after T -> true end.
● A timeout value can be 0. Good for flushing mailboxes:
flush_mailbox() ->
receive _Any -> flush_buffer()
after 0 -> true
end.
● Any pattern in the receive clause can have a when guard.
10
Example: Timer
-module(timer).
-export([start/2, cancel/1]).
start(Time, Fun) -> spawn(fun()->timer(Time, Fun) end).
cancel(Pid) -> Pid ! cancel.
timer(Time, Fun) ->
receive
cancel -> void
after Time -> Fun()
end.
11
Registered processes
● A pid can be published. A process with a published pid becomes a
registered process.
● register(atom, Pid)
– Register the process Pid with the name atom.
● unregister(atom)
– Remove the registration. If a registered process dies it will be
automatically unregistered.
● whereis(atom) -> Pid | undefined
– Find out whether atom is registered, and if so, what's its Pid
● registered() -> AtomList
– Return a list of all registered processes
12
Registered processes: example
1> Pid = spawn(fun area_server:loop/0).
<0.51.0>
2> register(area, Pid).
True
3> area ! {rectangle, 4, 5}.
A=20
{rectangle, 4, 5}
13
Concurrent Program: a Skeleton
-module(template).
-compile(export_all).
start() -> spawn(fun() -> loop([]) end).
rpc(Pid, Request) ->
Pid ! {self(), Request},
receive
{Pid, Response} -> Response
end.
loop(X) ->
receive
Any -> io:format(“Received: ~p~n”, [Any]),
loop(X) %% Tail recursion becomes a loop!
end.
14
Linking processes
● If a process in some way depends on another, then it may keep an eye
on the health of that second process using links and monitors
● Built-in function (BIF) link(Pid) links processes
● BIF spawn_link(Fun) -> Pid spawns a linked process—to avoid race
conditions
● BIF unlink(Pid) unlinks linked processes
● If A and B are linked and one of them dies, the other receives an exit
signal and will die, too—unless it is a system process
● A system process can trap exit signals
● BIF process_flag(trap_exit, true) makes a process a system process
15
on_exit handler: example
%% If Pid dies, execute Fun in yet another process
on_exit (Pid, Fun) ->
spawn(fun() ->
process_flag(trap_exit, true),
link(Pid),
receive
{'EXIT', Pid, Why} ->
Fun(Why)
end
end).
16
A keep-alive process
%% This function will keep a registered process alive!
keep_alive(Name, Fun) ->
register(Name, Pid = spawn(Fun)),
on_exit(Pid, fun(_Why) -> keep_alive(Name, Fun) end).
%% Unfortunately, this code has a race condition:
%% The new process can dies before the handler is registered!
17
Going distributed
● Distributed programs run on networks of computers and coordinate
their activities only by message passing
● Reasons for having distributed programs:
– Performance
– Reliability
– Scalability
– Support for intrinsically distributed applications (games, chats)
– Fun :)
● Trusted or untrusted environment? Distributed Erlang vs TCP/IP
sockets
18
Development sequence
● Write and test a program in a regular nondistributed Erlang session
● Test the program on several different Erlang nodes running on the
same computer
● Test the program on several different Erlang nodes running on several
physically separated computers either in the same local area network
or anywhere on the Internet
19
A simple key-value server (kvs)
-module(kvs).
-export([start/0,store/2,lookup/1]).
start()->register(kvs, spawn(fun()->loop() end)).
store(Key, Value)->rpc({store, Key, Value}).
lookup(Key) -> rpc({lookup, Key}).
rpc(Q)-> .... %% as defined earlier
loop() ->
receive
{From, {store, Key, Value}} -> put(Key, {ok, Value}),
From ! {kvs, true}, loop();
{From, {lookup, Key}} -> From ! {kvs, get(Key)}, loop()
end.
20
Running locally
1> kvs:start().
True
2> kvs:store({location, joe}, “Stockholm”).
True
3> kvs:lookup({location, joe}).
{ok, “Stockholm”}
4> kvs:lookup({location, jane}).
Undefined
21
A better rpc
● Standard Erlang libraries have packages rpc that provides a number of
remote procedure call services, and global that has functions for the
registration of names and locks (if necessary)
● call(Name, Mod, Function, ArgList) -> Result | {badrpc, Reason}
● For two Erlang nodes to communicate, they must share the same
cookie:
– put the cookie in ~/.erlang.cookie (make it user-readable)
– start Erlang shell with -setcookie parameter
– use erlang:set_cookie(node(), C) BIF
22
Two nodes, same host
astra:~/Erlang/> erl -sname aspera
Erlang (BEAM) emulator version 5.6.5 [source] [async-threads:0] [hipe]
[kernel-poll:false]
Eshell V5.6.5 (abort with ^G)
(aspera@astra)1> kvs:start().
true
---------------------------------------------------------------------
astra:~/Erlang/> erl -sname astra
Erlang (BEAM) emulator version 5.6.5 [source] [async-threads:0] [hipe]
[kernel-poll:false]
Eshell V5.6.5 (abort with ^G)
(astra@astra)1> rpc:call(aspera@astra,kvs,store,[weather,fine]).
true
(astra@astra)2> rpc:call(aspera@astra,kvs,lookup,[weather]).
{ok,fine}
23
Two nodes, two different hosts
● Start Erlang with the -name parameter (not -sname)
● Ensure that both nodes have the same cookie
● Make sure that DNS works
● Make sure that both hosts have the same version of the code that you
want to run
– Simply copy the code
– Use network file system (NFS)
– Use a code server (advanced)
– Use the shell command nl(Mod). This loads the module Mod on all
connected nodes.
24
More distribution primitives
● disconnect_node(Node) -> bool() | ignored
– forcefully disconnects a node
● node() -> Node
– returns the name of the local node
● node(Arg) -> Node
– returns the node where Arg (a PID, a reference, or a port) is located
● nodes() -> [Node]
– returns a list of all other connected nodes
● is_alive() -> bool()
– returns true if the local node is alive
25
Remote spawn
● spawn(Node,Fun) -> Pid
– this works exactly like spawn(Fun)—but remotely
● spawn(Node, Mod, Func, ArgList) -> Pid
– same as above; this function will not break if the distributed nodes
do not run exactly the same version of a particular module
● spawn_link(Node, Func) -> Pid
● spawn_link(Node, Mod, Func, ArgList)
26
A note on security
● Distributed Erlang should be used only in a trusted environment
● In an unstrusted network, use TCP/IP (module gen_tcp) or UDP/IP
(module gen_udp) sockets
27
Using TCP: example 1 (client)
%% socket_example.erl
nano_get_url() -> nano_get_url(“www.google.com”).
nano_get_url(Host) ->
{ok, Socket} = gen_tcp:connect(Host,80,[binary, {packet, 0})],
ok = gen_tcp:send(Socket, “GET / HTTP/1.0rnrn”),
receive_data(Socket, []).
receive_data(Socket, SoFar) ->
receive
{tcp,Socket,Bin} -> receive_data(Socket, [Bin|SoFar]);
{tcp_closed,Socket} -> list_to_binary(reverse(SoFar))
end.
%% On the shell command line:
1> string:tokens(binary_to_list(socket_examples:nano_get_url),”rn”).
%% But of course there is a standard function http:request(Url) !
28
Using TCP: example 2 (server)
%% socket_examples.erl
start_nano_server() ->
{ok, Listen} = gen_tcp:listen (2345, [binary, {packet, 4},
{reuseaddr, true}, {active, true}]),
{ok, Socket} = gen_tcp:accept (Listen),
gen_tcp:close (Listen),
loop (Socket).
loop(Socket) ->
receive
{tcp, Socket, Bin} -> io:format(“~p received~n”, [Bin]),
Str = binary_to_term(Bin), %% unmarshalling
...
gen_tcp:send(Socket, term_to_binary(Reply)),
loop(Socket). %% Tail recursion!
{tcp_closed, Socket} -> io:format(“Socket closed~n”)
end.
29
Programming with files
● Erlang supports (through module file):
– Reading all Erlang terms from a file at once
– Reading Erlang terms from a file one at a time and writing them
back
– Reading files line by line and writing lines into a file
– Reading an entire file into a binary and writing a binary to a file
– Reading files randomly
– Getting file info
– Working with directories
– Copying and deleting files
30
This presentation roughly covers the second 27
pages (of the total of 29
) of
“Programming Erlang. Software for a Concurrent World,” by Joe
Armstrong.

More Related Content

What's hot

VHDL- gate level modelling
VHDL- gate level modellingVHDL- gate level modelling
VHDL- gate level modelling
VandanaPagar1
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentalsHCMUTE
 
Arduino - Classes and functions
Arduino - Classes and functionsArduino - Classes and functions
Arduino - Classes and functions
Emertxe Information Technologies Pvt Ltd
 
Java Simple Programs
Java Simple ProgramsJava Simple Programs
Java Simple Programs
Upender Upr
 
Clojure 7-Languages
Clojure 7-LanguagesClojure 7-Languages
Clojure 7-Languages
Pierre de Lacaze
 
Clojure concurrency
Clojure concurrencyClojure concurrency
Clojure concurrency
Alex Navis
 
Functional solid
Functional solidFunctional solid
Functional solid
Matt Stine
 
Learning Functional Programming Without Growing a Neckbeard
Learning Functional Programming Without Growing a NeckbeardLearning Functional Programming Without Growing a Neckbeard
Learning Functional Programming Without Growing a Neckbeard
Kelsey Gilmore-Innis
 
Verilog
VerilogVerilog
Verilog
abkvlsi
 
Deuce STM - CMP'09
Deuce STM - CMP'09Deuce STM - CMP'09
Deuce STM - CMP'09
Guy Korland
 
Verilog overview
Verilog overviewVerilog overview
Verilog overview
posdege
 
Introduction To Erlang Final
Introduction To Erlang   FinalIntroduction To Erlang   Final
Introduction To Erlang FinalSinarShebl
 
Giorgio zoppi cpp11concurrency
Giorgio zoppi cpp11concurrencyGiorgio zoppi cpp11concurrency
Giorgio zoppi cpp11concurrency
Giorgio Zoppi
 
Why we cannot ignore Functional Programming
Why we cannot ignore Functional ProgrammingWhy we cannot ignore Functional Programming
Why we cannot ignore Functional ProgrammingMario Fusco
 
Java ppt
Java pptJava ppt
Java ppt
Rohan Gajre
 
Kotlin
KotlinKotlin

What's hot (20)

Crash course in verilog
Crash course in verilogCrash course in verilog
Crash course in verilog
 
VHDL- gate level modelling
VHDL- gate level modellingVHDL- gate level modelling
VHDL- gate level modelling
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentals
 
Arduino - Classes and functions
Arduino - Classes and functionsArduino - Classes and functions
Arduino - Classes and functions
 
Java Simple Programs
Java Simple ProgramsJava Simple Programs
Java Simple Programs
 
Clojure 7-Languages
Clojure 7-LanguagesClojure 7-Languages
Clojure 7-Languages
 
Clojure concurrency
Clojure concurrencyClojure concurrency
Clojure concurrency
 
Functional solid
Functional solidFunctional solid
Functional solid
 
Java Generics
Java GenericsJava Generics
Java Generics
 
Learning Functional Programming Without Growing a Neckbeard
Learning Functional Programming Without Growing a NeckbeardLearning Functional Programming Without Growing a Neckbeard
Learning Functional Programming Without Growing a Neckbeard
 
Verilog
VerilogVerilog
Verilog
 
Deuce STM - CMP'09
Deuce STM - CMP'09Deuce STM - CMP'09
Deuce STM - CMP'09
 
Verilog overview
Verilog overviewVerilog overview
Verilog overview
 
Introduction To Erlang Final
Introduction To Erlang   FinalIntroduction To Erlang   Final
Introduction To Erlang Final
 
Giorgio zoppi cpp11concurrency
Giorgio zoppi cpp11concurrencyGiorgio zoppi cpp11concurrency
Giorgio zoppi cpp11concurrency
 
Why we cannot ignore Functional Programming
Why we cannot ignore Functional ProgrammingWhy we cannot ignore Functional Programming
Why we cannot ignore Functional Programming
 
Assembler
AssemblerAssembler
Assembler
 
Verilog hdl
Verilog hdlVerilog hdl
Verilog hdl
 
Java ppt
Java pptJava ppt
Java ppt
 
Kotlin
KotlinKotlin
Kotlin
 

Viewers also liked

Pregătirea materialelor
Pregătirea materialelorPregătirea materialelor
Pregătirea materialelorMihaela Anton
 
September 2016 Newsletter
September 2016 NewsletterSeptember 2016 Newsletter
September 2016 Newsletter
Chris Norton
 
Planeaciones
PlaneacionesPlaneaciones
Planeaciones
Aureliia villanueva
 
Thermal Blitz
Thermal BlitzThermal Blitz
Thermal Blitz
Marc Dupuis
 
The P4 of Networkacy
The P4 of NetworkacyThe P4 of Networkacy
The P4 of Networkacy
Dmitry Zinoviev
 
Ebpf ovsconf-2016
Ebpf ovsconf-2016Ebpf ovsconf-2016
Ebpf ovsconf-2016
Cheng-Chun William Tu
 
Ensiklopedi Fotografi Lembah Koerintji
Ensiklopedi Fotografi Lembah KoerintjiEnsiklopedi Fotografi Lembah Koerintji
Ensiklopedi Fotografi Lembah Koerintji
Kiting is Curly
 
ANTREC Moldova (ru)
ANTREC Moldova (ru)ANTREC Moldova (ru)
ANTREC Moldova (ru)
ANTREC Moldova
 
Functional Programing
Functional ProgramingFunctional Programing
Functional Programing
Max Arshinov
 
Beam me up, Scotty
Beam me up, ScottyBeam me up, Scotty
Beam me up, Scotty
Gianluca Padovani
 
QCON SP 2016 - Elixir: Tolerância a Falhas para Adultos
QCON SP 2016 - Elixir: Tolerância a Falhas para AdultosQCON SP 2016 - Elixir: Tolerância a Falhas para Adultos
QCON SP 2016 - Elixir: Tolerância a Falhas para Adultos
Fabio Akita
 
Parsing binaries and protocols with erlang
Parsing binaries and protocols with erlangParsing binaries and protocols with erlang
Parsing binaries and protocols with erlang
Bhasker Kode
 
end user programming & yahoo pipes
end user programming & yahoo pipesend user programming & yahoo pipes
end user programming & yahoo pipes
Bhasker Kode
 
in-memory capacity planning, Erlang Factory London 09
in-memory capacity planning, Erlang Factory London 09in-memory capacity planning, Erlang Factory London 09
in-memory capacity planning, Erlang Factory London 09
Bhasker Kode
 

Viewers also liked (20)

Expo "Reptile vii"
Expo "Reptile vii"Expo "Reptile vii"
Expo "Reptile vii"
 
Pregătirea materialelor
Pregătirea materialelorPregătirea materialelor
Pregătirea materialelor
 
September 2016 Newsletter
September 2016 NewsletterSeptember 2016 Newsletter
September 2016 Newsletter
 
Exchanging gifts
Exchanging giftsExchanging gifts
Exchanging gifts
 
Planeaciones
PlaneacionesPlaneaciones
Planeaciones
 
scan0007
scan0007scan0007
scan0007
 
Thermal Blitz
Thermal BlitzThermal Blitz
Thermal Blitz
 
Projeto séc. xviii
Projeto séc. xviiiProjeto séc. xviii
Projeto séc. xviii
 
The P4 of Networkacy
The P4 of NetworkacyThe P4 of Networkacy
The P4 of Networkacy
 
Ebpf ovsconf-2016
Ebpf ovsconf-2016Ebpf ovsconf-2016
Ebpf ovsconf-2016
 
Ensiklopedi Fotografi Lembah Koerintji
Ensiklopedi Fotografi Lembah KoerintjiEnsiklopedi Fotografi Lembah Koerintji
Ensiklopedi Fotografi Lembah Koerintji
 
Der Zugdes Lebens
Der Zugdes LebensDer Zugdes Lebens
Der Zugdes Lebens
 
ANTREC Moldova (ru)
ANTREC Moldova (ru)ANTREC Moldova (ru)
ANTREC Moldova (ru)
 
User-centered design
User-centered designUser-centered design
User-centered design
 
Functional Programing
Functional ProgramingFunctional Programing
Functional Programing
 
Beam me up, Scotty
Beam me up, ScottyBeam me up, Scotty
Beam me up, Scotty
 
QCON SP 2016 - Elixir: Tolerância a Falhas para Adultos
QCON SP 2016 - Elixir: Tolerância a Falhas para AdultosQCON SP 2016 - Elixir: Tolerância a Falhas para Adultos
QCON SP 2016 - Elixir: Tolerância a Falhas para Adultos
 
Parsing binaries and protocols with erlang
Parsing binaries and protocols with erlangParsing binaries and protocols with erlang
Parsing binaries and protocols with erlang
 
end user programming & yahoo pipes
end user programming & yahoo pipesend user programming & yahoo pipes
end user programming & yahoo pipes
 
in-memory capacity planning, Erlang Factory London 09
in-memory capacity planning, Erlang Factory London 09in-memory capacity planning, Erlang Factory London 09
in-memory capacity planning, Erlang Factory London 09
 

Similar to Introduction to Erlang Part 2

Multiplatform JIT Code Generator for NetBSD by Alexander Nasonov
Multiplatform JIT Code Generator for NetBSD by Alexander NasonovMultiplatform JIT Code Generator for NetBSD by Alexander Nasonov
Multiplatform JIT Code Generator for NetBSD by Alexander Nasonov
eurobsdcon
 
Kernel Recipes 2019 - Formal modeling made easy
Kernel Recipes 2019 - Formal modeling made easyKernel Recipes 2019 - Formal modeling made easy
Kernel Recipes 2019 - Formal modeling made easy
Anne Nicolas
 
Process management
Process managementProcess management
Process management
Akshay Ithape
 
Challenges in GPU compilers
Challenges in GPU compilersChallenges in GPU compilers
Challenges in GPU compilers
AnastasiaStulova
 
Os lab final
Os lab finalOs lab final
Os lab final
LakshmiSarvani6
 
04_ForkPipe.pptx
04_ForkPipe.pptx04_ForkPipe.pptx
04_ForkPipe.pptx
vnwzympx
 
Erlang/OTP in Riak
Erlang/OTP in RiakErlang/OTP in Riak
Erlang/OTP in Riak
Sargun Dhillon
 
Big Data for Mobile
Big Data for MobileBig Data for Mobile
Big Data for MobileBugSense
 
Linux Systems Programming: Process CommunCh11 Processes and Signals
Linux Systems Programming: Process CommunCh11 Processes and SignalsLinux Systems Programming: Process CommunCh11 Processes and Signals
Linux Systems Programming: Process CommunCh11 Processes and Signals
RashidFaridChishti
 
Node js lecture
Node js lectureNode js lecture
Node js lecture
Darryl Sherman
 
掀起 Swift 的面紗
掀起 Swift 的面紗掀起 Swift 的面紗
掀起 Swift 的面紗
Pofat Tseng
 
Os2 2
Os2 2Os2 2
Os2 2issbp
 
Erlang
ErlangErlang
Erlang
ESUG
 
02 functions, variables, basic input and output of c++
02   functions, variables, basic input and output of c++02   functions, variables, basic input and output of c++
02 functions, variables, basic input and output of c++
Manzoor ALam
 
Build reliable, traceable, distributed systems with ZeroMQ
Build reliable, traceable, distributed systems with ZeroMQBuild reliable, traceable, distributed systems with ZeroMQ
Build reliable, traceable, distributed systems with ZeroMQ
Robin Xiao
 
Lock? We don't need no stinkin' locks!
Lock? We don't need no stinkin' locks!Lock? We don't need no stinkin' locks!
Lock? We don't need no stinkin' locks!Michael Barker
 
Locks? We Don't Need No Stinkin' Locks - Michael Barker
Locks? We Don't Need No Stinkin' Locks - Michael BarkerLocks? We Don't Need No Stinkin' Locks - Michael Barker
Locks? We Don't Need No Stinkin' Locks - Michael Barker
JAX London
 
Erlang
ErlangErlang

Similar to Introduction to Erlang Part 2 (20)

Multiplatform JIT Code Generator for NetBSD by Alexander Nasonov
Multiplatform JIT Code Generator for NetBSD by Alexander NasonovMultiplatform JIT Code Generator for NetBSD by Alexander Nasonov
Multiplatform JIT Code Generator for NetBSD by Alexander Nasonov
 
Kernel Recipes 2019 - Formal modeling made easy
Kernel Recipes 2019 - Formal modeling made easyKernel Recipes 2019 - Formal modeling made easy
Kernel Recipes 2019 - Formal modeling made easy
 
Process management
Process managementProcess management
Process management
 
Challenges in GPU compilers
Challenges in GPU compilersChallenges in GPU compilers
Challenges in GPU compilers
 
Os lab final
Os lab finalOs lab final
Os lab final
 
Npc14
Npc14Npc14
Npc14
 
04_ForkPipe.pptx
04_ForkPipe.pptx04_ForkPipe.pptx
04_ForkPipe.pptx
 
Erlang/OTP in Riak
Erlang/OTP in RiakErlang/OTP in Riak
Erlang/OTP in Riak
 
Big Data for Mobile
Big Data for MobileBig Data for Mobile
Big Data for Mobile
 
Linux Systems Programming: Process CommunCh11 Processes and Signals
Linux Systems Programming: Process CommunCh11 Processes and SignalsLinux Systems Programming: Process CommunCh11 Processes and Signals
Linux Systems Programming: Process CommunCh11 Processes and Signals
 
Node js lecture
Node js lectureNode js lecture
Node js lecture
 
掀起 Swift 的面紗
掀起 Swift 的面紗掀起 Swift 的面紗
掀起 Swift 的面紗
 
Os2 2
Os2 2Os2 2
Os2 2
 
Erlang
ErlangErlang
Erlang
 
Appsec obfuscator reloaded
Appsec obfuscator reloadedAppsec obfuscator reloaded
Appsec obfuscator reloaded
 
02 functions, variables, basic input and output of c++
02   functions, variables, basic input and output of c++02   functions, variables, basic input and output of c++
02 functions, variables, basic input and output of c++
 
Build reliable, traceable, distributed systems with ZeroMQ
Build reliable, traceable, distributed systems with ZeroMQBuild reliable, traceable, distributed systems with ZeroMQ
Build reliable, traceable, distributed systems with ZeroMQ
 
Lock? We don't need no stinkin' locks!
Lock? We don't need no stinkin' locks!Lock? We don't need no stinkin' locks!
Lock? We don't need no stinkin' locks!
 
Locks? We Don't Need No Stinkin' Locks - Michael Barker
Locks? We Don't Need No Stinkin' Locks - Michael BarkerLocks? We Don't Need No Stinkin' Locks - Michael Barker
Locks? We Don't Need No Stinkin' Locks - Michael Barker
 
Erlang
ErlangErlang
Erlang
 

More from Dmitry Zinoviev

Machine Learning Basics for Dummies (no math!)
Machine Learning Basics for Dummies (no math!)Machine Learning Basics for Dummies (no math!)
Machine Learning Basics for Dummies (no math!)
Dmitry Zinoviev
 
WHat is star discourse in post-Soviet film journals?
WHat is star discourse in post-Soviet film journals?WHat is star discourse in post-Soviet film journals?
WHat is star discourse in post-Soviet film journals?
Dmitry Zinoviev
 
The “Musk” Effect at Twitter
The “Musk” Effect at TwitterThe “Musk” Effect at Twitter
The “Musk” Effect at Twitter
Dmitry Zinoviev
 
Are Twitter Networks of Regional Entrepreneurs Gendered?
Are Twitter Networks of Regional Entrepreneurs Gendered?Are Twitter Networks of Regional Entrepreneurs Gendered?
Are Twitter Networks of Regional Entrepreneurs Gendered?
Dmitry Zinoviev
 
Using Complex Network Analysis for Periodization
Using Complex Network Analysis for PeriodizationUsing Complex Network Analysis for Periodization
Using Complex Network Analysis for Periodization
Dmitry Zinoviev
 
Algorithms
AlgorithmsAlgorithms
Algorithms
Dmitry Zinoviev
 
Text analysis of The Book Club Play
Text analysis of The Book Club PlayText analysis of The Book Club Play
Text analysis of The Book Club Play
Dmitry Zinoviev
 
Exploring the History of Mental Stigma
Exploring the History of Mental StigmaExploring the History of Mental Stigma
Exploring the History of Mental Stigma
Dmitry Zinoviev
 
Roles and Words in a massive NSSI-Related Interaction Network
Roles and Words in a massive NSSI-Related Interaction NetworkRoles and Words in a massive NSSI-Related Interaction Network
Roles and Words in a massive NSSI-Related Interaction Network
Dmitry Zinoviev
 
“A Quaint and Curious Volume of Forgotten Lore,” or an Exercise in Digital Hu...
“A Quaint and Curious Volume of Forgotten Lore,” or an Exercise in Digital Hu...“A Quaint and Curious Volume of Forgotten Lore,” or an Exercise in Digital Hu...
“A Quaint and Curious Volume of Forgotten Lore,” or an Exercise in Digital Hu...
Dmitry Zinoviev
 
Network analysis of the 2016 USA presidential campaign tweets
Network analysis of the 2016 USA presidential campaign tweetsNetwork analysis of the 2016 USA presidential campaign tweets
Network analysis of the 2016 USA presidential campaign tweets
Dmitry Zinoviev
 
Network Analysis of The Shining
Network Analysis of The ShiningNetwork Analysis of The Shining
Network Analysis of The Shining
Dmitry Zinoviev
 
The Lord of the Ring. A Network Analysis
The Lord of the Ring. A Network AnalysisThe Lord of the Ring. A Network Analysis
The Lord of the Ring. A Network Analysis
Dmitry Zinoviev
 
Pickling and CSV
Pickling and CSVPickling and CSV
Pickling and CSV
Dmitry Zinoviev
 
Python overview
Python overviewPython overview
Python overview
Dmitry Zinoviev
 
Welcome to CS310!
Welcome to CS310!Welcome to CS310!
Welcome to CS310!
Dmitry Zinoviev
 
Programming languages
Programming languagesProgramming languages
Programming languages
Dmitry Zinoviev
 
DaVinci Code. Network Analysis
DaVinci Code. Network AnalysisDaVinci Code. Network Analysis
DaVinci Code. Network Analysis
Dmitry Zinoviev
 
Soviet Popular Music Landscape: Community Structure and Success Predictors
Soviet Popular Music Landscape: Community Structure and Success PredictorsSoviet Popular Music Landscape: Community Structure and Success Predictors
Soviet Popular Music Landscape: Community Structure and Success Predictors
Dmitry Zinoviev
 
C for Java programmers (part 2)
C for Java programmers (part 2)C for Java programmers (part 2)
C for Java programmers (part 2)
Dmitry Zinoviev
 

More from Dmitry Zinoviev (20)

Machine Learning Basics for Dummies (no math!)
Machine Learning Basics for Dummies (no math!)Machine Learning Basics for Dummies (no math!)
Machine Learning Basics for Dummies (no math!)
 
WHat is star discourse in post-Soviet film journals?
WHat is star discourse in post-Soviet film journals?WHat is star discourse in post-Soviet film journals?
WHat is star discourse in post-Soviet film journals?
 
The “Musk” Effect at Twitter
The “Musk” Effect at TwitterThe “Musk” Effect at Twitter
The “Musk” Effect at Twitter
 
Are Twitter Networks of Regional Entrepreneurs Gendered?
Are Twitter Networks of Regional Entrepreneurs Gendered?Are Twitter Networks of Regional Entrepreneurs Gendered?
Are Twitter Networks of Regional Entrepreneurs Gendered?
 
Using Complex Network Analysis for Periodization
Using Complex Network Analysis for PeriodizationUsing Complex Network Analysis for Periodization
Using Complex Network Analysis for Periodization
 
Algorithms
AlgorithmsAlgorithms
Algorithms
 
Text analysis of The Book Club Play
Text analysis of The Book Club PlayText analysis of The Book Club Play
Text analysis of The Book Club Play
 
Exploring the History of Mental Stigma
Exploring the History of Mental StigmaExploring the History of Mental Stigma
Exploring the History of Mental Stigma
 
Roles and Words in a massive NSSI-Related Interaction Network
Roles and Words in a massive NSSI-Related Interaction NetworkRoles and Words in a massive NSSI-Related Interaction Network
Roles and Words in a massive NSSI-Related Interaction Network
 
“A Quaint and Curious Volume of Forgotten Lore,” or an Exercise in Digital Hu...
“A Quaint and Curious Volume of Forgotten Lore,” or an Exercise in Digital Hu...“A Quaint and Curious Volume of Forgotten Lore,” or an Exercise in Digital Hu...
“A Quaint and Curious Volume of Forgotten Lore,” or an Exercise in Digital Hu...
 
Network analysis of the 2016 USA presidential campaign tweets
Network analysis of the 2016 USA presidential campaign tweetsNetwork analysis of the 2016 USA presidential campaign tweets
Network analysis of the 2016 USA presidential campaign tweets
 
Network Analysis of The Shining
Network Analysis of The ShiningNetwork Analysis of The Shining
Network Analysis of The Shining
 
The Lord of the Ring. A Network Analysis
The Lord of the Ring. A Network AnalysisThe Lord of the Ring. A Network Analysis
The Lord of the Ring. A Network Analysis
 
Pickling and CSV
Pickling and CSVPickling and CSV
Pickling and CSV
 
Python overview
Python overviewPython overview
Python overview
 
Welcome to CS310!
Welcome to CS310!Welcome to CS310!
Welcome to CS310!
 
Programming languages
Programming languagesProgramming languages
Programming languages
 
DaVinci Code. Network Analysis
DaVinci Code. Network AnalysisDaVinci Code. Network Analysis
DaVinci Code. Network Analysis
 
Soviet Popular Music Landscape: Community Structure and Success Predictors
Soviet Popular Music Landscape: Community Structure and Success PredictorsSoviet Popular Music Landscape: Community Structure and Success Predictors
Soviet Popular Music Landscape: Community Structure and Success Predictors
 
C for Java programmers (part 2)
C for Java programmers (part 2)C for Java programmers (part 2)
C for Java programmers (part 2)
 

Recently uploaded

Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Crescat
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
Adele Miller
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
wottaspaceseo
 
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
Alina Yurenko
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
XfilesPro
 
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
Juraj Vysvader
 
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdfAutomated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
timtebeek1
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Globus
 
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdfVitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke
 
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI AppAI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
Google
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
Fermin Galan
 
Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"
Donna Lenk
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
Ortus Solutions, Corp
 
Text-Summarization-of-Breaking-News-Using-Fine-tuning-BART-Model.pptx
Text-Summarization-of-Breaking-News-Using-Fine-tuning-BART-Model.pptxText-Summarization-of-Breaking-News-Using-Fine-tuning-BART-Model.pptx
Text-Summarization-of-Breaking-News-Using-Fine-tuning-BART-Model.pptx
ShamsuddeenMuhammadA
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
Globus
 
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissancesAtelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Neo4j
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
Globus
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke
 

Recently uploaded (20)

Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
 
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
 
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
 
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdfAutomated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
 
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdfVitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdf
 
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI AppAI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
 
Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
 
Text-Summarization-of-Breaking-News-Using-Fine-tuning-BART-Model.pptx
Text-Summarization-of-Breaking-News-Using-Fine-tuning-BART-Model.pptxText-Summarization-of-Breaking-News-Using-Fine-tuning-BART-Model.pptx
Text-Summarization-of-Breaking-News-Using-Fine-tuning-BART-Model.pptx
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
 
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissancesAtelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissances
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
 

Introduction to Erlang Part 2

  • 2. 2 Concurrency ● A deep understanding of concurrency is “hardwired” into our brains ● The world is parallel ● Erlang programs model how we think and interact: – No shared memory ● People function as independent entities who communicate by sending messages: – Erlang is based on pure message passing – No locking needed ● If somebody dies, other people will notice: – Processes can be linked together
  • 3. 3 Erlang Processes ● Erlang processes belong to the programming language, not to the OS – Creating and destroying processes is very fast – Sending messages between processes is very fast – Processes behave the same way on all operating systems – A very large number of processes is feasible – Processes share no memory and are completely independent – Creating a process takes 4–5ms – The only way for processes to interact is through message passing
  • 4. 4 Concurrency Primitives ● Pid = spawn(Fun) – Create a new concurrent process that evaluates Fun. The primitive returns the process identifier ● Pid ! Message – Send Message to the process Pid. The send is nonblocking (asynchronous). The value of the expression is the message itself. Therefore, Pid1 ! Pid2 ! ... ! PidN ! M sends M to all mentioned processes ● receive ... end – Receive a message according to a pattern.
  • 5. 5 A Simple Example %% area_server.erl -module(area_server). -export([loop/0]). loop()-> receive {rectangle, Width, Ht} -> io:format(“A=~p~n”,[Width*Ht]), loop(); {circle, R} -> io:format(“A=~p~n”,[3.14159*R*R]), loop(); Other -> io:format(“Error: ~p~n”, [Other]), loop() end. %% Usage: 1> Pid = spawn(fun area_server:loop/0). <0.36.0> 2> Pid ! {rectangle, 6, 10}. A=60 {rectangle, 6, 10}
  • 6. 6 Client-server ● Actually, “request-response” ● To receive a response, a request must contain the pid of the requester ● Received responses must be matched with pending requests with the help of pid's and, if necessary, sequence numbers ● Requests can be disguised as (remote) procedure calls
  • 7. 7 Client-server example %% area_server_final.erl -module(area_server_final). -export([start/0,area/2]). start() -> spawn(fun loop/0). area(Pid, What) -> rpc(Pid, What). rpc(Pid, Request) -> Pid ! {self(), Request}, receive {Pid, Response} -> Response End. loop() -> receive {From, {rectangle, W, H}} -> From ! {self(), W*H}, loop(); %%.... end.
  • 8. 8 Client-server example (cont.) %% At shell prompt 1> Pid = area_server_final:start(). <0.36.0> 2> area_server_final:area(Pid, {rectangle, 10, 8}). 80
  • 9. 9 Receive with timeout and guards ● receive...end can have and optional after clause that takes Time in milliseconds and returns an expression if no message is received after Time. Time can be infinity. ● The receive clause itself can be empty. Good for timers: sleep(T) -> receive after T -> true end. ● A timeout value can be 0. Good for flushing mailboxes: flush_mailbox() -> receive _Any -> flush_buffer() after 0 -> true end. ● Any pattern in the receive clause can have a when guard.
  • 10. 10 Example: Timer -module(timer). -export([start/2, cancel/1]). start(Time, Fun) -> spawn(fun()->timer(Time, Fun) end). cancel(Pid) -> Pid ! cancel. timer(Time, Fun) -> receive cancel -> void after Time -> Fun() end.
  • 11. 11 Registered processes ● A pid can be published. A process with a published pid becomes a registered process. ● register(atom, Pid) – Register the process Pid with the name atom. ● unregister(atom) – Remove the registration. If a registered process dies it will be automatically unregistered. ● whereis(atom) -> Pid | undefined – Find out whether atom is registered, and if so, what's its Pid ● registered() -> AtomList – Return a list of all registered processes
  • 12. 12 Registered processes: example 1> Pid = spawn(fun area_server:loop/0). <0.51.0> 2> register(area, Pid). True 3> area ! {rectangle, 4, 5}. A=20 {rectangle, 4, 5}
  • 13. 13 Concurrent Program: a Skeleton -module(template). -compile(export_all). start() -> spawn(fun() -> loop([]) end). rpc(Pid, Request) -> Pid ! {self(), Request}, receive {Pid, Response} -> Response end. loop(X) -> receive Any -> io:format(“Received: ~p~n”, [Any]), loop(X) %% Tail recursion becomes a loop! end.
  • 14. 14 Linking processes ● If a process in some way depends on another, then it may keep an eye on the health of that second process using links and monitors ● Built-in function (BIF) link(Pid) links processes ● BIF spawn_link(Fun) -> Pid spawns a linked process—to avoid race conditions ● BIF unlink(Pid) unlinks linked processes ● If A and B are linked and one of them dies, the other receives an exit signal and will die, too—unless it is a system process ● A system process can trap exit signals ● BIF process_flag(trap_exit, true) makes a process a system process
  • 15. 15 on_exit handler: example %% If Pid dies, execute Fun in yet another process on_exit (Pid, Fun) -> spawn(fun() -> process_flag(trap_exit, true), link(Pid), receive {'EXIT', Pid, Why} -> Fun(Why) end end).
  • 16. 16 A keep-alive process %% This function will keep a registered process alive! keep_alive(Name, Fun) -> register(Name, Pid = spawn(Fun)), on_exit(Pid, fun(_Why) -> keep_alive(Name, Fun) end). %% Unfortunately, this code has a race condition: %% The new process can dies before the handler is registered!
  • 17. 17 Going distributed ● Distributed programs run on networks of computers and coordinate their activities only by message passing ● Reasons for having distributed programs: – Performance – Reliability – Scalability – Support for intrinsically distributed applications (games, chats) – Fun :) ● Trusted or untrusted environment? Distributed Erlang vs TCP/IP sockets
  • 18. 18 Development sequence ● Write and test a program in a regular nondistributed Erlang session ● Test the program on several different Erlang nodes running on the same computer ● Test the program on several different Erlang nodes running on several physically separated computers either in the same local area network or anywhere on the Internet
  • 19. 19 A simple key-value server (kvs) -module(kvs). -export([start/0,store/2,lookup/1]). start()->register(kvs, spawn(fun()->loop() end)). store(Key, Value)->rpc({store, Key, Value}). lookup(Key) -> rpc({lookup, Key}). rpc(Q)-> .... %% as defined earlier loop() -> receive {From, {store, Key, Value}} -> put(Key, {ok, Value}), From ! {kvs, true}, loop(); {From, {lookup, Key}} -> From ! {kvs, get(Key)}, loop() end.
  • 20. 20 Running locally 1> kvs:start(). True 2> kvs:store({location, joe}, “Stockholm”). True 3> kvs:lookup({location, joe}). {ok, “Stockholm”} 4> kvs:lookup({location, jane}). Undefined
  • 21. 21 A better rpc ● Standard Erlang libraries have packages rpc that provides a number of remote procedure call services, and global that has functions for the registration of names and locks (if necessary) ● call(Name, Mod, Function, ArgList) -> Result | {badrpc, Reason} ● For two Erlang nodes to communicate, they must share the same cookie: – put the cookie in ~/.erlang.cookie (make it user-readable) – start Erlang shell with -setcookie parameter – use erlang:set_cookie(node(), C) BIF
  • 22. 22 Two nodes, same host astra:~/Erlang/> erl -sname aspera Erlang (BEAM) emulator version 5.6.5 [source] [async-threads:0] [hipe] [kernel-poll:false] Eshell V5.6.5 (abort with ^G) (aspera@astra)1> kvs:start(). true --------------------------------------------------------------------- astra:~/Erlang/> erl -sname astra Erlang (BEAM) emulator version 5.6.5 [source] [async-threads:0] [hipe] [kernel-poll:false] Eshell V5.6.5 (abort with ^G) (astra@astra)1> rpc:call(aspera@astra,kvs,store,[weather,fine]). true (astra@astra)2> rpc:call(aspera@astra,kvs,lookup,[weather]). {ok,fine}
  • 23. 23 Two nodes, two different hosts ● Start Erlang with the -name parameter (not -sname) ● Ensure that both nodes have the same cookie ● Make sure that DNS works ● Make sure that both hosts have the same version of the code that you want to run – Simply copy the code – Use network file system (NFS) – Use a code server (advanced) – Use the shell command nl(Mod). This loads the module Mod on all connected nodes.
  • 24. 24 More distribution primitives ● disconnect_node(Node) -> bool() | ignored – forcefully disconnects a node ● node() -> Node – returns the name of the local node ● node(Arg) -> Node – returns the node where Arg (a PID, a reference, or a port) is located ● nodes() -> [Node] – returns a list of all other connected nodes ● is_alive() -> bool() – returns true if the local node is alive
  • 25. 25 Remote spawn ● spawn(Node,Fun) -> Pid – this works exactly like spawn(Fun)—but remotely ● spawn(Node, Mod, Func, ArgList) -> Pid – same as above; this function will not break if the distributed nodes do not run exactly the same version of a particular module ● spawn_link(Node, Func) -> Pid ● spawn_link(Node, Mod, Func, ArgList)
  • 26. 26 A note on security ● Distributed Erlang should be used only in a trusted environment ● In an unstrusted network, use TCP/IP (module gen_tcp) or UDP/IP (module gen_udp) sockets
  • 27. 27 Using TCP: example 1 (client) %% socket_example.erl nano_get_url() -> nano_get_url(“www.google.com”). nano_get_url(Host) -> {ok, Socket} = gen_tcp:connect(Host,80,[binary, {packet, 0})], ok = gen_tcp:send(Socket, “GET / HTTP/1.0rnrn”), receive_data(Socket, []). receive_data(Socket, SoFar) -> receive {tcp,Socket,Bin} -> receive_data(Socket, [Bin|SoFar]); {tcp_closed,Socket} -> list_to_binary(reverse(SoFar)) end. %% On the shell command line: 1> string:tokens(binary_to_list(socket_examples:nano_get_url),”rn”). %% But of course there is a standard function http:request(Url) !
  • 28. 28 Using TCP: example 2 (server) %% socket_examples.erl start_nano_server() -> {ok, Listen} = gen_tcp:listen (2345, [binary, {packet, 4}, {reuseaddr, true}, {active, true}]), {ok, Socket} = gen_tcp:accept (Listen), gen_tcp:close (Listen), loop (Socket). loop(Socket) -> receive {tcp, Socket, Bin} -> io:format(“~p received~n”, [Bin]), Str = binary_to_term(Bin), %% unmarshalling ... gen_tcp:send(Socket, term_to_binary(Reply)), loop(Socket). %% Tail recursion! {tcp_closed, Socket} -> io:format(“Socket closed~n”) end.
  • 29. 29 Programming with files ● Erlang supports (through module file): – Reading all Erlang terms from a file at once – Reading Erlang terms from a file one at a time and writing them back – Reading files line by line and writing lines into a file – Reading an entire file into a binary and writing a binary to a file – Reading files randomly – Getting file info – Working with directories – Copying and deleting files
  • 30. 30 This presentation roughly covers the second 27 pages (of the total of 29 ) of “Programming Erlang. Software for a Concurrent World,” by Joe Armstrong.