Concurrent programming in Erlang

59 sec read

Just want to share how simple is Erlang concurrent programming
Starting with an example of simple mathematical calculation in sequential programming
-module(calculator).
-export([add/2]).
add([Num1, num2]) -> Num1 + Num2 % method which adds the two numbers


If i compile and call the method it works fine
so how we do this using erlang processes (processes in erlang are small self-contained virtual machines which are fast and completely independent – no common memory sharing)
[source language=”ruby”]
-module(calculator).
-export([loop/0]).
loop() ->
receive
[Num1, Num2] -> io:format(“The total is “, [Num1 + Num2]),
loop();
end.
[/source]
We can create a process to evaluate
[source language=”ruby”]
Pid = spawn(fun calculator:loop/0).
Pid ! [3, 4] % should return 7
[/source]
Here spawn and ! are concurrent primitives used to create and send message to the process
Lets extend little further to have client server architecture.
[source language=”ruby”]
-module(calculator).
-export([loop/0, rpc/2]).
rpc(Pid, Request) ->
Pid ! {self(), Request},
receive
Response -> Response
end.
loop() ->
receive
{From, [Num1, Num2]} ->
From ! Num1 + Num2,
loop()
end.
[/source]
Here rpc is a utility function (short for remote procedure call) that encapsulates sending a request to a server and waiting for a response
Usually its not a good design for a process to wait for a response because all the erlang process only share information through message passing so during the waiting time the data get interchanged
the simplest way to resolve this is by adding a pattern matching in the rpc receive
{Pid, Response} ->
Response
and on the message call from the loop method should be like From ! {self(), Num1 + Num2}
Hope you like it.

Related posts:

Leave a Reply

Your email address will not be published. Required fields are marked *