Concurrency


Processes

code

start() ->
     Pid = spawn(fun run/0),
     io:format("Spawned ~p~n",[Pid]).

run() ->
 io:format("Hello!~n",[]).

Forking

BIF

Message passing

How does it work?

Forms of synchronization

Consider the behaviour of the sender of a message

Examples

Forms of naming

How do sender and receiver refer to each other when message passing is used?

Erlang message passing

Spawning and tail recursion

A simple echo-server

code

Indirect

-module(echo).
-export([start/0]).

echo() ->
    receive
    {From, Msg} -> 
        From ! {self(), Msg},
        echo();
    stop ->
        true
    end.

start() ->
    Pid = spawn(fun echo/0),
    % sending tokens to the server
    Token = 42, 
    Pid ! {self(), Token},
    io:format("Sent~w~n",[Token]),
    receive 
       {Pid, Msg} ->
            io:format("Received ~w~n", [Msg]) 
    end,
    % stop server
    Pid ! stop.    

Reacting to multiple messages

Sources of multiple messages

Selective receive

receive 
  {Pid, Ref, N} when N>0 -> ...